gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:59:31 26 4
gpt4 key购买 nike

在反射接口(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com