【问题标题】:Is it possible to test whether an interface inheits another interface using reflection?是否可以使用反射测试一个接口是否继承另一个接口?
【发布时间】:2017-02-07 15:58:45
【问题描述】:

所以我有以下Interface

public interface Interface2 : Interface1
{
   //Properties here
}

还有一个Class 像这样:

public class MyClass
{
   public Interface2 MyDataAccess { get; set; }

   public void TestInheritance()
   {
        foreach (var property in typeof(MyClass).GetProperties())
        {
            var type = property.PropertyType;
            var inheritsproperty = type.IsAssignableFrom(typeof(Interface1));
            if (type is Interface1 || inheritsproperty)
            {
                //never hit
            }
        }
   }
}

看着它,我希望上面的代码可以工作,

inheritsProperty 属性始终为假,type is Interface1 始终为假。

那么是否可以使用反射来检查一个接口是否继承了另一个接口?我做错了什么?

【问题讨论】:

  • type is Interface1 不是您使用is 运算符的方式。它用于检查实例是否与类型(msdn.microsoft.com/en-us/library/scekt9xw.aspx)兼容。要比较类型,请使用 typeof 和相等运算符,例如。 type == typeof(Interface1 ).
  • 部分为真,比较为真,但type == typeof(Interface1 )只有当type == interface1
  • 正确。要同时检查继承树,应该使用IsAssignableFrom()
  • 您只需检查IsAssignableFrom(),因为:typeof(Interface1).IsAssignableFrom(typeof(Interface1)) == true

标签: c# inheritance reflection interface


【解决方案1】:

你应该交换类型:(tested)

var inheritsproperty = type.IsAssignableFrom(typeof(Interface1));

应该是:

var inheritsproperty = typeof(Interface1).IsAssignableFrom(type);

这个名字有点含糊,但上面写着Can you assign <parameter> to the caller/source type.


制作:

public class MyClass
{
   public Interface2 MyDataAccess { get; set; }

   public void TestInheritance()
   {
        foreach (var property in typeof(MyClass).GetProperties())
        {
            var type = property.PropertyType;

            var inheritsproperty = typeof(Interface1).IsAssignableFrom(type);

            if (inheritsproperty)
            {
                //does hit
            }
        }
   }
}

【讨论】:

    猜你喜欢
    • 2010-12-13
    • 1970-01-01
    • 2012-05-21
    • 2021-08-20
    • 2012-08-24
    • 2012-01-20
    • 2015-12-23
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多