小编mni*_*eld的帖子

在C#中使用Reflection进行转换

我已经创建了一个通用函数,如下所示(仅作为证明),它将采用一个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();
}
Run Code Online (Sandbox Code Playgroud)

证明的目的是我只知道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 });
Run Code Online (Sandbox Code Playgroud)

这里有两个问题:

  1. 在第二行,而不是提供typeof(int),我希望提供类似于somthign myList.GetType().GetGenericArguments()[0].GetType(),以使事情更灵活,因为我T直到运行时才知道.当Invoke运行时,执行此操作会导致运行时错误,如下所示:"System.Collections.Generic.List'1 [System.Int32]类型的对象'无法转换为类型'System.Collections.Generic.List'1 [ System.RuntimeType]"."
  2. Invoke() …

.net c# reflection

4
推荐指数
1
解决办法
3550
查看次数

标签 统计

.net ×1

c# ×1

reflection ×1