【发布时间】:2012-11-02 11:25:11
【问题描述】:
我正在尝试围绕接口进行思考。我一直在暗示这样的事情:
public interface IFoo
{
ICollection<IBar> Bars { get; set; }
//some other properties
}
public interface IBar
{
//some properties
}
//assume Bar is implemented and extends IBar. Some instaces of Bar are created
Bar[] MyBars = {bar1, bar2};
Foo MyFoo = new Foo();
MyFoo.Bars=MyBars.ToList(); //This causes an error saying Collection<Bar> cannot be
//assigned to ICollection<IBar>.
我完全不知道如何正确地做到这一点。填充接口集合的正确方法是什么?
编辑:我实现 Foo 的方式可能是问题的一部分。
public class Foo : IFoo
{
public ICollection<IBar> Bars { get; set; }
}
【问题讨论】:
-
您是否尝试使用 Collection
而不是 ICollection ? -
@Fuex foo 类可能是问题的一部分。一分钟。
-
您正在尝试将
Bar的集合放入IBar的集合中。编译器不能假定接口可以隐式转换。 -
我接受了他的评论://假设 Foo 和 Bar 已实现并扩展 IFoo 和 IBar,并创建了一些 //Bar 的实例 ... 以表明他已经知道并且已经这样做了。
-
你试过我下面的建议了吗?
标签: c# interface icollection