c#接口实现 – 为什么这不构建?
发布时间:2020-12-15 20:48:42 所属栏目:百科 来源:网络整理
导读:很抱歉,如果之前已经询问过,但谷歌几乎不可能.我认为int数组实现IEnumerable,因此Thing应该能够实现IThing.怎么没有? public interface IThing{ IEnumerableint Collection { get; }}public class Thing : IThing{ public int[] Collection { get; set; }}
很抱歉,如果之前已经询问过,但谷歌几乎不可能.我认为int数组实现IEnumerable,因此Thing应该能够实现IThing.怎么没有?
public interface IThing { IEnumerable<int> Collection { get; } } public class Thing : IThing { public int[] Collection { get; set; } } 注意 public class Thing : IThing { public int[] Array { get; set; } public IEnumerable<int> Collection { get { return this.Array; } } } 很好. 解决方法
接口实现必须完全实现接口.这可以防止您返回实现该接口的类型作为成员.
如果您希望这样做,一个选项是明确实现接口: public interface IThing { IEnumerable<int> Collection { get; } } public class Thing : IThing { public int[] Collection { get; set; } IEnumerable<int> IThing.Collection { get { return this.Collection; } } } 这允许类的公共API使用具体类型,但接口实现要正确实现. 例如,有了上述内容,您可以编写: internal class Test { private static void Main(string[] args) { IThing thing = new Thing { Collection = new[] { 3,4,5 } }; foreach (var i in thing.Collection) { Console.WriteLine(i); } Console.ReadKey(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |