【问题标题】:Check if a classes Property or Method is declared as sealed检查类属性或方法是否被声明为密封
【发布时间】: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


【解决方案1】:

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

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

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

来自 MSDN 的一些注释:

要确定一个方法是否可重写,仅检查IsVirtual 是否为真是不够的。对于可覆盖的方法,IsVirtual 必须为真,IsFinal 必须为假。例如,一个方法可能是非虚拟的,但它实现了一个接口方法。公共语言运行时要求所有实现接口成员的方法都必须标记为虚拟;因此,编译器将方法标记为 virtual final。所以在某些情况下,方法被标记为虚拟但仍然不可覆盖。

【讨论】:

    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多