gpt4 book ai didi

c# - 为什么 C# Type.GetProperty() 对接口(interface)的行为与对基类的行为不同?

转载 作者:太空狗 更新时间:2023-10-29 23:08:46 32 4
gpt4 key购买 nike

如果类型是接口(interface),为什么 Type.GetProperty(string) 不从基接口(interface)获取属性?例如,以下代码打印:

System.String X
null
System.String X
System.String X

这看起来不一致:

void Main()
{
Console.WriteLine(typeof(I1).GetProperty("X"));
Console.WriteLine(typeof(I2).GetProperty("X"));
Console.WriteLine(typeof(C1).GetProperty("X"));
Console.WriteLine(typeof(C2).GetProperty("X"));;
}

public interface I1 { string X { get; } }

public interface I2 : I1 { }

public class C1 { public string X { get { return "x"; } } }

public class C2 : C1 { }

编辑支持 Cole 答案的运行时的另一个方面如下:

public class C : I2 {
// not allowed: the error is
// 'I2.X' in explicit interface declaration is not a member of interface
string I2.X { get; set; }

// allowed
string I1.X { get; set; }
}

最佳答案

请记住,类继承与接口(interface)实现不同。

派生类及其基类具有is-a 关系。如果 D : B 那么 D 是一个 B。如果 B 有一个属性,那么 D 根据定义也将具有相同的属性,因为这就是那种关系的意思D 的“实质”在某种意义上被它与 B 的关系改变了。

接口(interface)不提供实现,所以当你说 ID : IB 时,你并不是真的在说 ID 是一个 IB 与处理类的方式相同。这甚至意味着什么? IDIB 不是事物;它们是协议(protocol)。没有什么可以改变的。相反,您是说“实现 ID 的类还必须为 IB 提供实现。”

ID 派生自 IB 的事实不会更改 ID,因为它没有可更改的内容。这只是意味着任何 promise 履行 ID 指定的契约(Contract)的类也必须准备好遵守一组额外的要求。

牢记这一点,如果 IB 提供属性 X,则正确回答“ID 是否具有属性 X ?”是ID 要求您还实现 IB,它确实具有属性 X,但它本身没有属性 X

关于c# - 为什么 C# Type.GetProperty() 对接口(interface)的行为与对基类的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15419590/

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