我试图解决在C#中返回类型协方差的支持不足的问题,如this问题及其前两个答案中所述。大多数情况下,我在设置演员时没有任何问题,但是使用对象/接口列表的一个属性妨碍了我的努力。之间的列表<MyType>和列表之间施展<IMyType>
我需要做什么才能使IFoo.manyBars
的演员阵容工作?
public interface IBar
{
}
public interface IFoo
{
IBar aBar { get; set; }
IEnumerable<IBar> manyBars { get; set; }
}
class CBar : IBar
{
}
class CFoo : IFoo
{
public CBar aBar { get; set; }
//this cast works
IBar IFoo.aBar
{
get { return aBar; }
set { aBar = (CBar)value; }
}
public List<CBar> manyBars { get; set; }
//the compiler can't cast either of these
List<IBar> IFoo.manyBars
{
get { return (List<IBar>)manyBars; }
set { manyBars = (List<CBar>)value; }
}
}
将我的界面切换到IEnumerable不是问题,这样做会避免使用Linq来执行强制转换结果的问题。 –
2010-11-15 21:06:17
- 类的用户将无法删除项目,因为'IEnumerable'接口暴露无删除机制。所以对用户而言,它会*不会令人惊讶,因为他们甚至不能*尝试*删除项目。 –
cdhowie
2010-11-15 21:12:38
我想我可以忍受,因为IFoo/IBar消费者就是我想要封装的东西,并且向接口添加/删除方法似乎不会造成任何主要问题。 CFoo和COtherFoo应用程序的其余部分可以继续使用列表 /列表版本。 –
2010-11-15 21:22:31