收藏的隐式转换 [英] Implicit conversion of collections
本文介绍了收藏的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我定义两种类型之间的显式转换运营商,不应该跟随它,我可以明确这些类型的集合之间的转换? IE浏览器。
If I define an explicit conversion operator between two types, shouldn't it follow that I can explicitly convert between collections of those types? Ie.
public static explicit operator FooEntity(Entity entity)
{
FooEntity e = new FooEntity(entity);
return e;
}
就这样,我能做到这一点,
And thus I could do this,
IEnumerable<Entity> entities = GetEntities();
IEnumerable<FooEntity> fooEntities = (IEnumerable<FooEntity>)entities;
或
IEnumerable<FooEntity> fooEntities = entities as IEnumerable<FooEntity>
这是可能以某种方式或者我也可以创建自己的操作者集合之间的转换?我收到写着转换是不可能的运行时错误。
Is this possible somehow or do I also have to create my own operator to convert between the collections? I am getting a run-time error that says the conversion is not possible.
感谢。
推荐答案
C#不支持此的一般方法在收集分配类型差异,你将不得不使用这样的:
C# does not support this method of generic type variance on collection assignment, you'll have to use something like:
IEnumerable<FooEntity> fooEntities = entities.Select(e => (FooEntity)e);
这篇关于收藏的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文