我有以下推导:
interface IMyInterface
{
string myProperty {get;}
}
class abstract MyBaseClass : IMyInterface // Base class is defining myProperty as abstract
{
public abstract string myProperty {get;}
}
class Myclass : MyBaseClass // Base class is defining myProperty as abstract
{
public sealed override string myProperty
{
get { return "value"; }
}
}
我希望能够检查一个类的成员是否被声明为密封的。有点像这样:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
bool isSealed = property.GetMethod.IsSealed; // IsSealed does not exist
所有这一切的意义在于能够运行测试,检查代码/项目的一致性。
以下测试失败:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
Assert.IsFalse(property.GetMethod.IsVirtual);
最佳答案
听起来你想断言一个方法不能被覆盖。在那种情况下,您需要 IsFinal
的组合和 IsVirtual
属性:
PropertyInfo property = typeof(Myclass).GetProperty("myProperty")
Assert.IsTrue(property.GetMethod.IsFinal || !property.GetMethod.IsVirtual);
来自 MSDN 的一些注释:
To determine if a method is overridable, it is not sufficient to check that
IsVirtual
is true. For a method to be overridable,IsVirtual
must be true andIsFinal
must be false. For example, a method might be non-virtual, but it implements an interface method. The common language runtime requires that all methods that implement interface members must be marked as virtual; therefore, the compiler marks the method virtual final. So there are cases where a method is marked as virtual but is still not overridable.
关于c# - 检查类属性或方法是否声明为密封的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38078948/