创建通用列表<T>带反射 [英] Create generic List&lt;T&gt; with reflection

查看:28
本文介绍了创建通用列表<T>带反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性 IEnumerable 的类.如何创建一个创建新 List 并分配该属性的通用方法?

I have a class with a property IEnumerable<T>. How do I make a generic method that creates a new List<T> and assigns that property?

IList list = property.PropertyType.GetGenericTypeDefinition()
    .MakeGenericType(property.PropertyType.GetGenericArguments())
    .GetConstructor(Type.EmptyTypes);

我不知道 T 类型在哪里可以是任何东西

I dont know where is T type can be anything

推荐答案

假设你知道属性名,并且你知道它是一个 IEnumerable 那么这个函数会将它设置为一个列表对应类型:

Assuming you know the property name, and you know it is an IEnumerable<T> then this function will set it to a list of corresponding type:

public void AssignListProperty(Object obj, String propName)
{
  var prop = obj.GetType().GetProperty(propName);
  var listType = typeof(List<>);
  var genericArgs = prop.PropertyType.GetGenericArguments();
  var concreteType = listType.MakeGenericType(genericArgs);
  var newList = Activator.CreateInstance(concreteType);
  prop.SetValue(obj, newList);
}

请注意,此方法不进行类型检查或错误处理.我把它留给用户作为练习.

Please note this method does no type checking, or error handling. I leave that as an exercise to the user.

这篇关于创建通用列表<T>带反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆