MethodBase.IsFinal 屬性

定義

取得值,指出這個方法是否為 final

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

屬性值

如果這個方法為 final 則為 true;否則為 false

實作

範例

下列範例會顯示 falseIsFinal,這可能會導致您認為 MyMethod 可覆寫。 即使未標示 virtual MyMethod,程式代碼仍會列印false,因此無法覆寫。

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.Reflection

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

備註

如果虛擬方法標示 final為 ,則無法在衍生類別中覆寫它。 覆寫的虛擬方法可以使用 C# 中的 sealed 關鍵詞、Visual Basic 中的 NotOverridable 關鍵詞或 C++/CLI 中的 sealed 關鍵詞來標記final。 方法也可以由編譯程式隱含標示 final 。 例如,方法可能會在程式代碼中定義為非虛擬,但它會實作介面方法。 Common Language Runtime 要求實作介面成員的所有方法都必須標示為 virtual,因此編譯程式會標記 方法 virtual final

您可以搭配 IsVirtual 屬性使用這個屬性,以判斷方法是否可覆寫。 若要讓方法可覆寫, IsVirtual 屬性必須是 true ,而且 IsFinal 屬性必須是 false。 若要確定方法是否可覆寫,請使用如下的程序代碼:

if (MethodInfo.IsVirtual && !MethodInfo.IsFinal)
If MethodInfo.IsVirtual AndAlso Not MethodInfo.IsFinal Then

如果 IsVirtualfalseIsFinaltrue,則無法覆寫 方法。

適用於

另請參閱