c#在运行时动态创建通用列表

时间:2016-07-12 12:50:00

标签: c# list generic-list

按照this post上的示例,我发现了如何动态创建泛型类型列表。 现在,我的问题是我想从未知来源列表添加项目到创建的列表 - 有什么方法可以实现这一点吗?

修改 我从包含业务对象的源列表开始,但我绝对需要正确的输出列表类型,因为下游绑定需要它。

我的非编译代码如下:

    // BluetoothDevice device= BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:1C:4D:02:A6:55");
    // You already have a device so capture the method then invoke a socket
    Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
    socket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1));
    socket.connect();
    // Do some cool stuff

2 个答案:

答案 0 :(得分:6)

这个代码不起作用的原因有几个。

首先,您需要创建具体类型的实例。您正在使用非通用接口(IList)并尝试从中创建泛型类型。您需要typeof(List<>)

其次,您正在调用AddItem,而IList上的方法不是Add。您需要调用IList<object> sourceList; // some list containing custom objects Type t = typeof(List<>).MakeGenericType(sourceList[0].GetType()); IList res = (IList)Activator.CreateInstance(t); foreach(var item in sourceList) { res.Add(item); } ,这就是代码无法编译的原因。

此代码将执行您想要的操作:

sourceList[0]

但是,res保持正确类型的假设可能会让你感到困惑。如果该列表包含与列表中第一项不兼容的对象序列,则添加到List<object>的任何尝试都将失败。正如评论中提到的,您最好创建一个 string.append(new String(data, 0, bytesRead)) 来保存这些项目。

答案 1 :(得分:2)

我建议将代码移动到通用类或函数中,将反射移到更高级别:

private static List<T> CloneListAs<T>(IList<object> source)
{
    // Here we can do anything we want with T
    // T == source[0].GetType()
    return source.Cast<T>().ToList();
}

要打电话:

IList<object> sourceList; // some list containing custom objects
// sourceList = ...

MethodInfo method = typeof(this).GetMethod("CloneListAs");
MethodInfo genericMethod = method.MakeGenericMethod(sourceList[0].GetType());

var reportDS = genericMethod.Invoke(null, new[] {sourceList});