这个问题已经有了答案:
GetProperties() to return all properties for an interface inheritance hierarchy
6个答案
How to do proper Reflection of base Interface methods
3个答案
为什么当t是派生接口时,typeof(t).getproperties()没有找到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只显示一个属性?
谢谢您
恩里克

最佳答案

这是因为接口不是相互“派生”的;把它们看作实现类必须遵守的契约。因此,当你有这个:

interface IFoo : IBar { }

这并不意味着IFoo本身具有与IBar相同的成员。这意味着IFoo的任何实现者也承担实现IBar的责任。从实现者的角度来看,这种区别听起来像是精细的打印,但它确实对类型系统产生了非常重要的区别。
如果您想明确地找出哪些属性必须由IDerivedOne的实现者定义,而不是由IDerivedOne声明的哪些属性定义,那么您需要考虑IDerivedOne,找到它的“基本”接口并递归地枚举它们的成员。

07-24 09:35