MethodBase.IsFinal MethodBase.IsFinal MethodBase.IsFinal MethodBase.IsFinal Property

定义

获取一个值,该值指示此方法是否为 finalGets a value indicating whether this method is final.

public:
 property bool IsFinal { bool get(); };
public bool IsFinal { get; }
member this.IsFinal : bool
Public ReadOnly Property IsFinal As Boolean

属性值

如果方法为 final,则为 true;否则为 falsetrue if this method is final; otherwise, false.

实现

示例

下面的示例显示falseIsFinal,这可能会导致您考虑 MyMethod 是可重写。The following example displays false for IsFinal, which might lead you to think that MyMethod is overridable. 该代码会输出false即使 MyMethod 未标记为virtual,因此不能重写。The code prints false even though MyMethod is not marked virtual and thus cannot be overridden.

using namespace System;
using namespace System::Reflection;

public ref class MyClass
{
public:
   void MyMethod(){}
};

int main()
{
   MethodBase^ m = MyClass::typeid->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 );
}
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);
    }
}
Imports System
Imports System.Reflection
Imports Microsoft.VisualBasic

Public Class MyClass1
    
    Public Sub MyMethod()
    End Sub
    
    Public Shared Sub Main()
        Dim m As MethodBase = GetType(MyClass1).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)
    End Sub
End Class

注解

若要确定是否可重写一个方法,不只需检查IsVirtualtrueTo determine if a method is overridable, it is not sufficient to check that IsVirtual is true. 该方法将被重写的对于IsVirtual必须是trueIsFinal必须是falseFor a method to be overridable, IsVirtual must be true and IsFinal must be false. 例如,一种方法可能是非虚拟的但它实现接口方法。For example, a method might be non-virtual, but it implements an interface method. 公共语言运行时需要实现接口成员的所有方法必须都标记为virtual; 因此,编译器将方法标记virtual finalThe common language runtime requires that all methods that implement interface members must be marked as virtual; therefore, the compiler marks the method virtual final. 因此有其中一个方法标记为virtual但仍然不可重写。So there are cases where a method is marked as virtual but is still not overridable.

若要建立明确地是否是可重写方法,请使用如下代码:To establish with certainty whether a method is overridable, use code such as this:

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

如果IsVirtualfalseIsFinaltrue,则不能重写该方法。If IsVirtual is false or IsFinal is true, then the method cannot be overridden.

适用于

另请参阅