[英]Casting an object to a IList with an abstract type parameter
In my code, I have an object: 在我的代码中,我有一个对象:
object obj = ...
Which I know is of type MyListType, where MyListType is a subclass of IList and T is a subclass of MyAbstractClass. 我知道类型为MyListType,其中MyListType是IList的子类,而T是MyAbstractClass的子类。 The type parameter of MyListType is constrained so that it is always a subclass of MyAbstractClass.
MyListType的类型参数受到约束,因此它始终是MyAbstractClass的子类。
However, trying to cast obj 但是,尝试投射obj
MyListType<MyAbstractClass> myList = (MyListType<MyAbstractClass>)obj;
gives a runtime error. 给出运行时错误。
I tried to define an explicit operator 我试图定义一个显式运算符
public static explicit operator MyListType<MyAbstractClass>(MyListType<T> list)
{
MyListType<MyAbstractClass> newList = new MyListType<MyAbstractClass>();
foreach(T t in list)
newList.Add((MyAbstractClass) t);
return newList;
}
However, this operator doesn't get used by the cast since obj is an object, not a MyListType. 但是,由于obj是一个对象而不是MyListType,因此该运算符不会被强制转换使用。 Is there a workaround to successfully perform this cast?
是否有解决方法才能成功执行此投射?
I've looked at this question , but their the list was of an unknown type. 我看了这个问题 ,但是他们的名单是未知的。
I ended up reworking my code so that I wouldn't have to do this, but the solution is to first cast it to an IEnumerable, and then add the IEnumerable to a list. 最后,我对代码进行了重新设计,因此不必这样做,但是解决方案是先将其转换为IEnumerable,然后将IEnumerable添加到列表中。
MyListType<MyAbstractClass> list = new MyListType<MyAbstractClass>();
IEnumerable<MyAbstractClass> enumerable = obj as IEnumerable<MyAbstractClass>;
list.AddRange(enumerable);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.