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

标签 c# generics reflection

<分区>

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

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 个属性?

谢谢

恩里克

最佳答案

那是因为接口(interface)不是相互“派生”的;将它们视为实现类必须遵守的契约。因此,当你有这个:

interface IFoo : IBar { }

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

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

关于c# - typeof(t).GetProperties() 当 t 是从另一个派生的接口(interface)时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21723488/

相关文章:

c# - 将 Word 保存为 UTF-8 编码的 HTML

c# - Application.Current.Resources 和 Resources 之间有什么区别

c# - ASP.Net MVC 网站和 Web API 作为单一实现

java - List<?> 与 List<Object> 不同时的示例

c# - 是否可以将 C# 编译为 IL 并将生成的 IL 反编译为 F#?

c# - 如何形成我的节点和树通用类

C# 使用反射获取通用对象(及其嵌套对象)的属性

arrays - 如何使用反射 API 在 TypeScript 中获取数组项类型?

.net - 如何判断类型 A 是否可隐式转换为类型 B

c# - 在 .Net 中恢复本地名称