0

我正在尝试围绕界面进行思考。我一直在尝试这样的事情:

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; }
}
4

4 回答 4

1

根据您的方式,您可以这样做:

ICollection<Bar> MyBars = new Bar[] {bar1, bar2};
MyFoo.Bars = MyBars;

您也可以这样做,以编程方式可能更适合您:

List<Bar> lstBar = new List<Bar>();
lstBar.Add(bar1);
lstBar.Add(bar2);
MyFoo.Bars = lstBar;

整个来源:

public interface IFoo
{
    ICollection<IBar> Bars { get; set; }
}
public interface IBar
{

}
public class Foo : IFoo
{
    public ICollection<IBar> Bars { get; set; }
}
public class Bar : IBar
{
}

class Program
{
    static void Main(string[] args)
    {
        IFoo myFoo = new Foo();
        List<IBar> lstBar = new List<IBar>();
        lstBar.Add(new Bar());
        myFoo.Bars = lstBar;
    }
}
于 2012-11-02T11:29:06.147 回答
1

问题是Foo应该是的类:

public class Foo : IFoo
{
    public ICollection<Bar> Bars { get; set; }
}

或者,如果您想使用ICollection<IBar>

IBar[] MyBars = { bar1, bar2 };
Foo MyFoo = new Foo( );
MyFoo.Bars = MyBars.ToList( );

或者更优雅的解决方案:

Bar[] MyBars = { bar1, bar2 };
Foo MyFoo = new Foo( );
MyFoo.Bars = MyBars.ToList<IBar>( ); //Cast from Bar to IBar

事实上,问题的发生是因为您无法转换ICollection<Bar>ICollection<IBar>.

于 2012-11-02T11:41:18.000 回答
1

您如何实现 Bars 属性在这里很重要。您不能将具体类型分配给接口类型。当您尝试进行 ToList 转换时,您正在将其转换为具体的列表类型并尝试将其分配给 ICollection 接口类型,因此会产生错误。

以下应该可以正常工作。

public class Foo:IFoo
{
    public ICollection<IBar> Bars { get; set; }
}

Bar bar1 = new Bar();
Bar bar2 = new Bar();
Bar[] MyBars = { bar1, bar2 };
Foo MyFoo = new Foo();
MyFoo.Bars = MyBars;
于 2012-11-02T11:47:18.237 回答
1

它不会以这种方式工作。看,ICollection<T>在 上不是协变的T,因此即使是ICollection<Bar>,也不是。ICollection<IBar>BarIBar

为什么会这样?想象一下,有一些Quux实施IBar。如果您可以分配ICollection<Bar>ICollection<IBar>,那么有人可以使用 将 aQuux插入到集合中ICollection<IBar>.Add,因为Quux也是一个IBar!但是集合是Bars 的集合,所以会破坏类型安全。

你应该试试

IBar[] MyBars = {bar1, bar2};

这样您MyBars就可以插入其他IBars,而不仅仅是Bars。

于 2012-11-02T11:55:30.287 回答