c# - 为什么使用反射无法使用继承接口(interface)的成员?

标签 c# reflection

在反射接口(interface)类型时,我只获取特定类型的成员,而不是继承的成员。

在这个过度简化的示例中,程序只打印“Name”,而不是我期望的“ItemNumber”、“Name”:

using System;

public interface IBasicItem
{
    string ItemNumber { get; set; }
}

public interface IItem : IBasicItem
{
    string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var type = typeof (IItem);
        foreach (var prop in type.GetProperties())
            Console.WriteLine(prop.Name);
    }
}

这背后的基本原理是什么?当我从基接口(interface)继承时,我是说我的接口(interface)的任何实现也必须实现继承的成员。换句话说,IItem 是一个 IBasicItem。那么为什么继承的成员不使用反射出现呢?

最佳答案

我认为这正是 Phil Haack 刚刚在博客中谈到的内容。

来自 ECMA-335 公共(public)语言基础设施规范:

8.9.11 Interface type derivation Interface types can require the implementation of one or more other interfaces. Any type that implements support for an interface type shall also implement support for any required interfaces specified by that interface. This is different from object type inheritance in two ways:

  • Object types form a single inheritance tree; interface types do not.
  • Object type inheritance specifies how implementations are inherited; required interfaces do not, since interfaces do not define implementation. Required interfaces specify additional contracts that an implementing object type shall support.

To highlight the last difference, consider an interface, IFoo, that has a single method. An interface, IBar, which derives from it, is requiring that any object type that supports IBar also support IFoo. It does not say anything about which methods IBar itself will have.

引用自: http://haacked.com/archive/2009/11/10/interface-inheritance-esoterica.aspx

关于c# - 为什么使用反射无法使用继承接口(interface)的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1783379/

相关文章:

c# - 具有序列 ID 的线程安全固定大小循环缓冲区

c# - 当整数部分大于 9 个字符时,小数点四舍五入的问题

go - 使用反射取消引用结构指针和访问字段

c# - 通过反射检查时缺少 NotNullAttribute

java - 如何通过反射获取类的 Array 字段?

c# - Visual Studio 连接字符串- 相对文件路径?

c# - 如何在XBAP/Prism中初始化Shell?

c# - 拥有兼容的接口(interface),无需继承

c# - 转换通过反射创建的类时遇到问题

Scala:有没有办法编写一个泛型函数,它返回带有泛型参数的泛型实例?