我正在尝试解决 C# 中缺乏对返回类型协方差支持的问题,如 this 中所述。问题及其前两个答案。在大多数情况下,我在设置强制转换时没有任何问题,但我使用对象/接口(interface)列表的一个属性阻碍了我的努力。
我需要做什么才能使 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; }
}
}
最佳答案
试试这个。您必须添加 using System.Linq;
到源文件的顶部(如果尚不存在)。
List<IBar> IFoo.manyBars
{
get { return manyBars.Cast<IBar>().ToList(); }
set { manyBars = value.Cast<CBar>().ToList(); }
}
请注意,这将在每次访问属性时分配并复制一个新数组。如果这不是您想要的,您应该考虑替代方法,例如使用类型 IEnumerable<IBar>
公开属性.
使用List<IBar>
也意味着有人可能会尝试做 anObject.manyBars.Remove(0)
这不会对 anObject
中存储的列表绝对没有任何作用 ,因为返回了副本。
关于c# - 在 List<MyType> 和 List<IMyType> 之间进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4188717/