我有过
public interface IFoo
{
IEnumerable<IThingy> Thingies{get;}
}我想这样才能做到
class Thing1 : IThingy
{
...
}
class ImplementFoo : IFoo
{
List<Thing1> m_things;
IEnumerable<IThingy> Thingies {get {return m_things;}}
}ImplementFoo.Thingies返回Thing1s (即IThings)的IList (即IEnumerable)。因此,从理论上讲,这段代码应该可以工作,但它不起作用。VS建议在getter中进行强制转换;这会编译,但在运行时失败。我是否对c# 4中的协方差期望过高?
VS 2010 -> Silverlight 4。
无法隐式地将类型“
System.Collections.Generic.List<MyProj.Column>”转换为“System.Collections.Generic.IEnumerable<MyProj.IColumn>”。存在显式转换(是否缺少强制转换?)
编辑:人们告诉我这应该有效,但在SL4中不起作用
发布于 2011-09-08 17:25:34
THis是SL4和CLR4的区别。THe IEnumerable接口未标记为“out”。显然是用SL5修复的
发布于 2011-07-22 23:26:11
这在C#/.NET 4中很好。下面是一个完整的编译和工作示例:
namespace Test
{
using System;
using System.Collections.Generic;
using System.Linq;
public interface IThingy { }
public interface IFoo
{
IEnumerable<IThingy> Thingies { get; }
}
internal class Thing1 : IThingy { }
internal class ImplementFoo : IFoo
{
private List<Thing1> m_things = new List<Thing1>() { new Thing1() };
public IEnumerable<IThingy> Thingies
{
get { return m_things; }
}
}
internal class Program
{
private static void Main(string[] args)
{
var impl = new ImplementFoo();
Console.WriteLine(impl.Thingies.Count());
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
}我怀疑问题在于您的目标是.NET 3.5sp1或更高版本,而不是.NET 4.0。协方差只有在以.NET 4为目标时才能正常工作,因为它需要新的框架更改。在本例中,IEnumerable<T> (在.NET 4中)实际上是IEnumerable,这是工作所必需的。
发布于 2011-07-22 23:25:50
您可以使用铸造拉伸法
class ImplementFoo : IFoo
{
List<Thing1> m_things;
IEnumerable<IThingy> Thingies
{
get
{
return m_things.Cast<IThingy>();
}
}
}这是因为IEnumerable<Thing1>没有隐式地实现IEnumerable<IThingy>。
https://stackoverflow.com/questions/6797098
复制相似问题