检查类Property或Method是否声明为sealed

时间:2016-06-28 14:26:12

标签: c# unit-testing testing reflection

我有以下推导:

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);

1 个答案:

答案 0 :(得分:5)

听起来你想断言一个方法不能被覆盖。在这种情况下,您需要IsFinalIsVirtual属性的组合:

PropertyInfo property = typeof(Myclass).GetProperty("myProperty")

Assert.IsTrue(property.GetMethod.IsFinal || !property.GetMethod.IsVirtual);

来自MSDN的一些说明:

  

要确定某个方法是否可以覆盖,仅检查IsVirtual是否为真是不够的。对于可覆盖的方法,IsVirtual必须为true且IsFinal必须为false。例如,方法可能是非虚拟的,但它实现了一个接口方法。公共语言运行库要求实现接口成员的所有方法都必须标记为虚拟;因此,编译器将方法标记为虚拟最终。因此,有些方法会将方法标记为虚拟,但仍然无法覆盖。