Implicit conversion of collections

扶醉桌前 提交于 2019-12-23 22:45:04

问题


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;

or

    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.

Thanks.


回答1:


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);


来源:https://stackoverflow.com/questions/5545524/implicit-conversion-of-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!