几年后回到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>
,所以我不确定为什么它不能满足。