MethodBase.IsFinal 屬性
本文內容
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得值,指出這個方法是否為 final
。
public:
property bool IsFinal { bool get(); };
public bool IsFinal { get; }
member this.IsFinal : bool
Public ReadOnly Property IsFinal As Boolean
如果這個方法為 final
則為 true
;否則為 false
。
下列範例會顯示 false
的 IsFinal
,這可能會導致您認為 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
如果 IsVirtual
為 false
或 IsFinal
為 true
,則無法覆寫 方法。
產品 | 版本 |
---|---|
.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 |