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

use*_*803 4 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 );
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

恩里克

Jon*_*Jon 5

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

interface IFoo : IBar { }
Run Code Online (Sandbox Code Playgroud)

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

如果您想要专门找出实现者必须定义IDerivedOne哪些属性IDerivedOne而不是声明您必须反映的属性IDerivedOne,请找到它的"基"接口并递归枚举其成员.