开发者

c# casting question

开发者 https://www.devze.com 2022-12-16 02:38 出处:网络
If I have the following classes: public class MyItems : List<MyItem> { .. } public class MyItem : Item

If I have the following classes:

public class MyItems : List<MyItem>
{
..
}

public class MyItem : Item
{
..
}

How could I go about casting an instance of My开发者_如何转开发Items back down to List<Item>? I've tried doing an explicit cast and I get an exception.


You can't, because C# doesn't support generic variance (see here for discussion of terminology), and even if it did, it wouldn't allow this case, because if you could cast MyItems to List<Item>, you could call Add(someItemThatIsntAMyItem), which would violate type safety (because a MyItems can contain only MyItem objects, not arbitrary items).

See this question (or search SO for "c# generic variance") for additional information about this issue and future changes in C# 4 (though these will not affect your specific case).


I believe I saw that was coming in 4.0. Not available yet.


public class MyList : IList<MyClass>
{
    List<MyClass> _list;


    //Implement all IList members like so
    public int IndexOf(MyClass item)
    {
        return _list.IndexOf(item);
    }


    //Then help the type system a bit with these two static methods.
    public static implicit operator List<MyClass> (MyList mylist)
    {
        return mylist._list;
    }

    public static implicit operator MyList (List<MyClass> list)
    {
        return new MyList() { _list = list;}
    }
0

精彩评论

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