我的目标是.NET框架的4.0版本。我写了下面的简单代码:通过反射和隐式转换创建通用列表
public class A
{
public A()
{
}
}
public class B
{
public B()
{
}
public static implicit operator A(B b)
{
return new A();
}
}
然后,我创建了一个通用的清单:
var mylist = typeof(List<>).MakeGenericType(typeof(A)).GetConstructor(Type.EmptyTypes).Invoke(new object[]{});
当我想补充的B
一个新的实例下面的代码工作:
((IList<A>)mylist).Add(new B());
然而如果我运行下面的代码,会抛出以下异常:
The value "B" is not of type "A" and cannot be used in this generic collection.
参数名:价值
((IList)mylist).Add(new B());
什么是你的问题? –
我该如何解决这个问题? –