【发布时间】:2018-07-30 05:13:57
【问题描述】:
几年后回到 C#,所以我有点生疏了。遇到这个(简化的)代码,让我头疼。
为什么必须显式实现IDataItem.Children 属性?普通的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>,所以我不知道为什么不满意。
【问题讨论】:
-
它不是“直接”使用的,有一个隐式转换(向上转换),编译器会将其转换为非零代码量。
-
Doesn't the normal Children property satisfy the requirement?- 不。根据我的理解,实现必须与接口签名完全匹配,包括返回类型。 -
C# 不支持返回类型协方差。
-
你不必明确地使用
IDataItem.Children,public IEnumerable<string> Children => new Collection<string>();就足够了。 -
@Guy:但是他无法从类内部将 Collection 对象用作 Collection :(