是否可以使用反射测试接口是否包含其他接口?

时间:2016-09-29 10:56:48

标签: c# inheritance reflection interface

所以我有以下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属性始终为false,type is Interface1始终为false。

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

1 个答案:

答案 0 :(得分:1)

您应该交换类型:(已测试)

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
            }
        }
   }
}
相关问题