c# – 为什么继承接口的成员不能使用反射?

在反映接口类型时,我只获取特定类型的成员,而不是继承成员.

在这个过于简化的例子中,程序只打印“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);
    }
}

这背后的理由是什么?当我从基接口继承时,我说我的接口的任何实现,也必须实现继承的成员.换句话说,IItem是一个IBasicItem.那么为什么继承的成员不会出现反射?

最佳答案
我认为这正是Phil Haack刚刚发表的博客.

从ECMA-335公共语言基础结构规范:

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# – 为什么继承接口的成员不能使用反射? - 代码日志