如何创建List <type>,其中Type是另一个对象Type </type>

时间:2011-04-21 05:31:48

标签: .net asp.net umbraco

E.G

List<Node> myNodeList<node>();
System.Type theType = myNodeList.GetType();
IEnumerable list<theType> = myNodeList;

1 个答案:

答案 0 :(得分:3)

//original list
List<Node> nodeList = new List<Node>();

// just get the type of the list
var nodeListType = nodeList.GetType();

// Create a new type for a list containing the original list.
var genericType = typeof (List<>).MakeGenericType(nodeListType);

// and instantiate it.
var listOfLists = (IEnumerable)Activator.CreateInstance(genericType);

你也可以制作通用版本:

public static IList<T> CreateOuterlist<T>(T innerList)
{
    return new List<T>();
}

List<Node> nodeList = new List<Node>();
var listOfLists = CreateOuterlist(nodeList);
listOfLists.Add(nodeList);