【发布时间】: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