开发者

Implicit conversion of collections

开发者 https://www.devze.com 2023-02-21 20:51 出处:网络
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.

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 c开发者_如何转开发reate my own operator to convert between the collections? I am getting a run-time error that says the conversion is not possible.

Thanks.


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

精彩评论

暂无评论...
验证码 换一张
取 消