【发布时间】:2014-02-07 10:34:11
【问题描述】:
我需要获取一种列表元素。
using System;
using System.Collections;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var xClass = new XClass();
xClass.Do();
}
}
public class XClass
{
public List<string> list1 = new List<string>();
public List<string> list2 { get; set; }
public void Do()
{
// first
Console.WriteLine("Type = {0}", GetListType(list1));
// second
var propertyList = this.GetType().GetProperty("list2"); // i get list from reflection
// Create instance of list2
var newList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(propertyList.PropertyType)));
Console.WriteLine("Type = {0}", GetListType(newList));
}
private Type GetListType(IEnumerable list)
{
return list.GetType().GetGenericArguments()[0];
}
}
输出:
Type = System.String
Type = System.Collections.Generic.List`1[System.String]
第二种情况我需要获取“System.String”
你可以在这里测试代码http://ideone.com/uLkfBx
【问题讨论】:
-
newList是List<List<string>>是故意的吗? -
提示:
propertyList.PropertyType是什么?尝试输出它。通常,不要只是尝试将各个部分拼凑在一起,而是要思考代码的作用。众所周知,它有时会提供帮助。 -
谢谢大家,我很笨:)