C# 处理无效的强制转换列表<;类型>;

C# 处理无效的强制转换列表<;类型>;,c#,reflection,C#,Reflection,我使用的是C#4.0,我在反射和投射方面有问题。我已经通读了几个关于StackOverflow的帖子,到目前为止,我还没有尝试过一个适合我的解决方案 问题是:我有一个类Character,它是从另一个类GenericDataObjectWithUniqueID派生的。我有一个字符列表(如,type list),我希望通过反射将它们作为 List<GenericDataObjectWithUniqueID>. 这将使我得到有问题的名单,没有问题,但作为一个IList。正如我所说,我

我使用的是C#4.0,我在反射和投射方面有问题。我已经通读了几个关于StackOverflow的帖子,到目前为止,我还没有尝试过一个适合我的解决方案

问题是:我有一个类Character,它是从另一个类GenericDataObjectWithUniqueID派生的。我有一个字符列表(如,type list),我希望通过反射将它们作为

List<GenericDataObjectWithUniqueID>. 
这将使我得到有问题的名单,没有问题,但作为一个IList。正如我所说,我想要的是列表

所以我试过这个:

(List<GenericDataObjectWithUniqueID>)p.GetValue(context, null);
这告诉我“参数1:无法从'System.Collections.IList'转换为'System.Collections.Generic.IEnumerable'”

我也试过:

IList propertyList = (IList)p.GetValue(context, null);
List<GenericDataObjectWithUniqueID> newList = propertyList as List<GenericDataObjectWithUniqueID>;
IList propertyList=(IList)p.GetValue(上下文,null);
List newList=propertyList as List;
这里没有错误,但“newList”为空

这些都是我们的建议,但到目前为止运气不好

我希望我只是错过了一些简单的事情。求你了,不,我不能直接用IList。我也试过了,但我还有代码需要使用

List<GenericDataObjectWithUniqueID>.
列表。

列表
不是协变的,因此
列表
不是
列表
。一个
List
是一个
IEnumerable
但是你可以这样做
var newList=newList((IEnumerable)p.GetValue(context,null))请注意:在使用反射之前,您可能应该首先探索更健壮、性能更好的方法来解决您的问题。
IList propertyList = (IList)p.GetValue(context, null);
List<GenericDataObjectWithUniqueID> newList = propertyList as List<GenericDataObjectWithUniqueID>;
List<GenericDataObjectWithUniqueID>.