typeof(t).GetProperties()当t是从另一个派生的接口时

时间:2014-02-12 09:19:47

标签: c# generics reflection

为什么typeof(t).GetProperties()在t是派生接口时找不到t的所有公共属性?这是预期的行为还是我遗漏了什么?

public interface IBaseOne
    {        int Id { get; }    }

public interface IDerivedOne : IBaseOne
    {        string Name { get; }    }

public class ImplementsIDerivedOne : IDerivedOne
    {
        public int Id { get; private set; }
        public string Name { get; private set; }
    }

public static class TypeOfTests
    {
        public static Type Testing<T>() where T : class,IBaseOne
        {
            return typeof(T);
        }
    }

class Program
{
    static void Main(string[] args)
    {
        Type typeFromIBaseOne = TypeOfTests.Testing<IBaseOne  >() ;
        Type typeFromIDerivedOne = TypeOfTests.Testing<IDerivedOne>();
        Type typeFromImplementsIDerivedOne = TypeOfTests.Testing<ImplementsIDerivedOne>();

        PropertyInfo[] propsFromIBaseOne = typeFromIBaseOne.GetProperties();
        PropertyInfo[] propsFromIDerivedOne = typeFromIDerivedOne.GetProperties();
        PropertyInfo[] propsFromImplementsIDerivedOne =TypeFromImplementsIDerivedOne.GetProperties();

        Debug.Print("From IBaseOne: {0} properties", propsFromIBaseOne.Length);
        Debug.Print("From IDerivedOne: {0} properties", propsFromIDerivedOne.Length);
        Debug.Print("From ImplementsIDerivedOne: {0} properties", propsFromImplementsIDerivedOne .Length );
    }
}

结果: 来自IBaseOne:1个属性 来自IDerivedOne:1个属性 来自ImplementsIDerivedOne:2个属性

为什么IDerivedOne只显示1个属性?

谢谢

恩里克

1 个答案:

答案 0 :(得分:5)

那是因为接口不会彼此“衍生”;将它们视为实施类必须遵守的合同。因此,当你有这个:

interface IFoo : IBar { }

这并不意味着IFoo本身与IBar具有相同的成员。这意味着 IFoo的任何实施者也承担了实施IBar 的责任。从实施者的角度来看,这种区别可能听起来很精细,但它确实对类型系统产生了非常重要的影响。

如果您想要专门找出必须由IDerivedOne 的实现者定义哪些属性而不是哪些属性IDerivedOne声明,您将必须反思IDerivedOne,找到它的“基础”接口并递归地枚举其成员。