c# - 检查类属性或方法是否声明为密封的

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

最佳答案

听起来你想断言一个方法不能被覆盖。在那种情况下,您需要 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 and IsFinal 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/

相关文章:

c# - 在分层列表中查找项目

c# - 将树结构解析为 If 语句

c# - 模拟 IOrganizationService (Dynamics CRM) 时未过滤 LINQ 查询结果

java - 正确配置以模拟 Hibernate 的 sessionFactory.getCurrentSession()

testing - 为什么 Jenkins 不正确地解析我的 JUnit 报告?

java - 在 Java 中测试并发性

android - 如果没有按钮,Espresso 不会记录任何 Intent

c# - 加密 App.Config 部分并部署到多台机器

c# - 将一个方法的属性用于另一个方法

java - 同行测试 - 有什么好的引用吗?