c# – 使用GenericTypeArgument在运行时更改类型

前端之家收集整理的这篇文章主要介绍了c# – 使用GenericTypeArgument在运行时更改类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我想要得到的
  1. (IList<Foo>)listPropertyInfo.GetValue(item)

这是我如何获得Foo类型

  1. listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0]

这是我试过但不能成功的

  1. Convert.ChangeType(listPropertyInfo.GetValue(item),IList<listPropertyInfo.GetValue(item).GetType().GenericTypeArguments[0]>)

这也是

  1. ((typeof(IList<>).MakeGenericType(listPropertyInfo.GetValue(item).GetType().GenericTypeArguments.Single())))(listPropertyInfo.GetValue(item))

这是我试图实现的方法

  1. public static void trigger(IList<T> result)
  2. {
  3. foreach (var item in result)
  4. {
  5. foreach (var listPropertyInfo in typeof(T).GetProperties().ToList().FindAll(x => x.PropertyType.Name == typeof(IList<>).Name))
  6. {
  7. trigger((IList<Foo>)listPropertyInfo.GetValue(item));
  8. }
  9. }
  10. }

解决方法

我这样解决
  1. IList targetList = (IList)listPropertyInfo.GetValue(item);
  2. Type foo = targetList.GetType().GenericTypeArguments.Single();
  3. Type unboundGenericType = typeof(READ<>);
  4. Type boundGenericType = unboundGenericType.MakeGenericType(foo);
  5. MethodInfo doSomethingMethod = boundGenericType.GetMethod("trigger");
  6. object instance = Activator.CreateInstance(boundGenericType);
  7. doSomethingMethod.Invoke(instance,new object[] { targetList,f,properties });

猜你在找的C#相关文章