gpt4 book ai didi

c# - TypeDescriptor 不从继承的接口(interface)返回成员

转载 作者:太空狗 更新时间:2023-10-30 00:17:02 27 4
gpt4 key购买 nike

我的问题是 TypeDescriptor 不从继承的接口(interface)返回成员,这是它应该如何工作的吗?还是错误?

 [TestFixture]
public class DescriptorTests
{
[Test]
public void Test()
{
// count = 1
Assert.AreEqual(2, TypeDescriptor.GetProperties(typeof(IFoo)).Count);
// it is going to fail, the Id is not going to be returned
}

public interface IEntity
{
int Id { get; set; }
}

public interface IFoo : IEntity
{
string Name { get; set; }
}
}

最佳答案

这不是错误。来自ECMA CLI specification :

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.

8.10 Member inheritance

Only object types can inherit implementations, hence only object types can inherit members (see §8.9.8). While interface types can be derived from other interface types, they only "inherit" the requirement to implement method contracts, never fields or method implementations.

编辑...

如果你想获取一个接口(interface)的属性,包括它的祖先的属性,那么你可以这样做:

var properties = typeof(IFoo)
.GetProperties()
.Union(typeof(IFoo)
.GetInterfaces()
.SelectMany(t => t.GetProperties()));

关于c# - TypeDescriptor 不从继承的接口(interface)返回成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4031267/

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