【发布时间】:2016-06-28 14:26:12
【问题描述】:
我有以下推导:
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);
【问题讨论】:
-
属性不能被密封。类可以。
-
bool isSealed = !property.GetMethod.IsVirtual; -
在 C# 中方法默认是“密封的”(不能被覆盖)。您必须将它们显式标记为
virtual,这就是为什么检查虚拟方法比检查“密封”方法更有意义的原因。 -
关键是,该方法实际上被标记为虚拟的。看看我的编辑。
-
@MarkusWeber 啊,我现在明白了。我添加了一个答案,因为该副本不适用于这种情况。
标签: c# unit-testing testing reflection