【发布时间】:2011-03-01 00:08:03
【问题描述】:
我创建了一个如下的通用函数(只是一个证明),它将采用 List<T> 集合并将其反转,返回一个新的 List<T> 作为其输出。
public static List<T> ReverseList<T>(List<T> sourceList)
{
T[] outputArray = new T[sourceList.Count];
sourceList.CopyTo(outputArray);
return outputArray.Reverse().ToList();
}
证明的目的是我只知道T在运行时是什么。因此,我使用反射来调用上述方法,如下所示:
List<int> myList = new List<int>() { 1, 2, 3, 4, 5 }; // As an example, but could be any type for T
MethodInfo myMethod = this.GetType().GetMethod("ReverseList");
MethodInfo resultMethod = myMethod.MakeGenericMethod(new Type[] { typeof(int) });
object result = resultMethod.Invoke(null, new object[] { myList });
这里有两个问题:
- 在第二行中,我想提供类似于
myList.GetType().GetGenericArguments()[0].GetType()的东西,而不是提供typeof(int),以使事情更灵活,因为直到运行时我才知道T。当 Invoke 按如下方式运行时,这样做会导致运行时错误:“'System.Collections.Generic.List'1[System.Int32]' 类型的对象无法转换为 'System.Collections.Generic.List'1[ System.RuntimeType]'。” -
Invoke()方法的结果返回一个对象。调试时,我可以看到该对象是 List 类型,但尝试使用它告诉我我有一个无效的演员表。我假设我需要使用反射将结果装箱为正确的类型(即在本例中,相当于(result as List<int>)。
有没有人可以帮助我解决这个问题?抱歉,如果不清楚,如果被问到,我可能会提供更多详细信息。
TIA
【问题讨论】:
-
等等...那你为什么不直接说
myList.GetType().GetGenericArguments()[0].GetType()? -
第二个框中的代码是打算放在泛型函数中,还是打算实际传递 Type 的实例?
-
啊,因为这导致异常如下:
"Object of type 'System.Collections.Generic.List1[System.Int32]' 不能转换为类型'System.Collections.Generic.List1[System.RuntimeType]'." -
@siride no 第二个框中的代码使用反射调用泛型方法。第 3 行即将更正,因为@Ben Voigt 对此部分有答案。
-
@mnield 那么我看不出问题出在哪里。您已经知道列表的类型,即
int。无需反射解决方案。
标签: c# .net reflection