C#-双协方差
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#-双协方差,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1520字,纯文字阅读大概需要3分钟。
内容图文
![C#-双协方差](/upload/InfoBanner/zyjiaocheng/654/d3157fea08d34af287c75d06b1f7772e.jpg)
我有
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建议使用吸气剂.可以编译,但在运行时失败.我在C#4中期望太多的协方差吗?
VS 2010-> Silverlight4.这是编译错误
Cannot implicitly convert type ‘
System.Collections.Generic.List<MyProj.Column>
‘ to ‘System.Collections.Generic.IEnumerable<MyProj.IColumn>
‘. An explicit conversion exists (are you missing a cast?)
编辑:人们告诉我这应该工作,但在SL4中不工作
解决方法:
在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时才能正常工作,因为它需要进行新的框架更改.在这种情况下,.NET 4中的IEnumerable T实际上为IEnumerable<out T>,这是工作所需的.
内容总结
以上是互联网集市为您收集整理的C#-双协方差全部内容,希望文章能够帮你解决C#-双协方差所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。