【问题标题】:typeof(t).GetProperties() when t is an interface that derives from another one [duplicate]typeof(t).GetProperties() 当 t 是从另一个派生的接口时[重复]
【发布时间】:2014-03-10 12:23:17
【问题描述】:

当 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 只显示 1 个属性?

谢谢

恩里克

【问题讨论】:

    标签: c# generics reflection


    【解决方案1】:

    这是因为接口不会相互“派生”;将它们视为实现类必须遵守的合同。因此,当你有这个时:

    interface IFoo : IBar { }
    

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

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

    【讨论】:

    • 感谢您的回答。现在很清楚了。恩里克
    猜你喜欢
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多