gpt4 book ai didi

c# - 为什么必须显式实现此接口(interface)?

转载 作者:可可西里 更新时间:2023-11-01 08:25:25 25 4
gpt4 key购买 nike

几年后回到 C#,所以我有点生疏了。遇到这个(简化的)代码,它让我摸不着头脑。

为什么必须显式实现 IDataItem.Children属性(property)?不正常Children属性满足要求?毕竟属性是直接用来满足的。为什么不是隐含的?

public interface IDataItem {

IEnumerable<string> Children { get; }
}

public class DataItem : IDataItem {

public Collection<string> Children { get; } = new Collection<string>();

// Why doesn't 'Children' above implement this automatically?!
// After all it's used directly to satisfy the requirement!
IEnumerable<string> IDataItem.Children => Children;
}

根据 C# 源代码,这里是 Collection<T> 的定义:

[System.Runtime.InteropServices.ComVisible(false)]
public class Collection<T> :
System.Collections.Generic.ICollection<T>,
System.Collections.Generic.IEnumerable<T>, <-- Right Here
System.Collections.Generic.IList<T>,
System.Collections.Generic.IReadOnlyCollection<T>,
System.Collections.Generic.IReadOnlyList<T>,
System.Collections.IList

如您所见,它显式地实现了 IEnumerable<T>根据我的理解,如果“X”实现“Y”,则“X” 是“Y”,所以 Collection<String> 一个IEnumerable<String>所以我不确定为什么不满意。

最佳答案

也许这个例子更清楚。我们希望签名完全1,2匹配,不允许替换,尽管类型之间存在任何继承关系。

我们不允许这样写:

public interface IDataItem {

void DoStuff(string value);
}

public class DataItem : IDataItem {

public void DoStuff(object value) { }
}

你的例子是一样的,除了你要求返回类型而不是参数(并且使用缩小而不是扩大转换,原因很明显)。尽管如此,同样的原则也适用。在匹配签名时,类型必须完全匹配3

你可以要求一种允许这样的事情发生的语言,这样的语言可能存在。但事实是,这些是 C# 的规则。


1在对 Co- and Contra-variance 的一些有限支持之外涉及泛型和接口(interface)/委托(delegate)。

2有些人可能会争论在这里使用签名是否是正确的词,因为在这种情况下,返回类型与参数类型、通用元数等一样重要;在大多数其他有人谈论 C# 方法签名的情况下,他们将明确忽略返回类型,因为他们(明确或隐含地)考虑重载规则所说的内容,以及对于重载,返回类型不是签名的一部分。

尽管如此,我还是很高兴在这里使用“签名”这个词。签名在 C# 规范中没有正式定义,在使用它的地方,通常会指出签名的哪些部分被考虑重载。

3更不用说如果您的 Children 会引发的问题方法返回 struct碰巧实现了IEnumerable<string> .现在您已经有了一个返回值类型的值的方法和一个调用者(通过 IDataItem 接口(interface),期望接收对象的引用

所以甚至不能按原样使用该方法。我们必须(在这种情况下)隐藏 装箱转换来实现接口(interface)。我相信,当对 C# 的这一部分进行规范时,他们是在努力避免让您自己轻松编写的代码有太多“隐藏的魔力”。

关于c# - 为什么必须显式实现此接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51587337/

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