MethodBase.IsFinal 属性

定义

获取一个值,该值指示此方法是否为 final

C#
public bool IsFinal { get; }

属性值

如果方法为 final,则为 true;否则为 false

实现

示例

以下示例显示 falseIsFinal这可能会导致你认为 MyMethod 是可重写的。 即使未标记 virtual MyMethod,代码也会打印false,因此无法重写。

C#
using System;
using System.Reflection;

public class MyClass
{
    public void MyMethod()
    {
    }
    public static void Main()
    {
        MethodBase m = typeof(MyClass).GetMethod("MyMethod");
        Console.WriteLine("The IsFinal property value of MyMethod is {0}.", m.IsFinal);
        Console.WriteLine("The IsVirtual property value of MyMethod is {0}.", m.IsVirtual);
    }
}

注解

如果虚拟方法标记为 final,则无法在派生类中重写它。 可以使用 C# 中的密封关键字 (keyword) 、Visual Basic 中的 NotOverridable 关键字 (keyword) 或 C++/CLI 中的密封关键字 (keyword) 来标记final重写的虚拟方法。 编译器还可以隐式标记 final 方法。 例如,方法可能在代码中定义为非虚拟方法,但它实现了接口方法。 公共语言运行时要求实现接口成员的所有方法都必须标记为 virtual;因此,编译器将方法 virtual final标记为 。

可以将此属性与 IsVirtual 属性结合使用,以确定方法是否可重写。 要使方法可重写,属性必须为 trueIsVirtualIsFinal属性必须为 false。 若要确定方法是否可重写,请使用如下代码:

C#
if (MethodInfo.IsVirtual && !MethodInfo.IsFinal)

如果 IsVirtualfalseIsFinaltrue,则无法重写方法。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅