【发布时间】:2015-12-25 14:57:35
【问题描述】:
到目前为止,我有这个:
if (o.GetType().IsGenericType && o is System.Collections.IEnumerable)
{
var typefield = typeof(List<object>).GetFields().Where(f => f.Name == "T").ToArray();
Type T = (Type)(typefield[0].GetValue(o));
addButton.Enabled = true;
if (((System.Collections.IList)o).Count > 0)
{
removeButton.Enabled = true;
}
comboBox1.Enabled = true;
comboBox1.Items.Clear();
foreach (var item in Assembly.GetAssembly(T).GetTypes().Where(x => T.IsAssignableFrom(x) && !x.IsAbstract))
{
comboBox1.Items.Add(item);
}
comboBox1.DisplayMember = "Name";
}
但它在“Type T = (Type)(typefield[0].GetValue(o));”行上崩溃因为数组是空的,也就是说上一行没有工作。
问题: 假设通过第一行的所有内容都是一个List,我应该如何确定列表中的对象类型。 (注意检查成员的类型是不够的。成员很可能是从列表定义中指定的 Type 派生的。)
附言 我在这里读到,我的第一行是将某些内容确定为列表的最佳方法: If object is Generic List 你有更准确的方法吗?
【问题讨论】:
-
可能应该是 typeof(System.Collections.IEnumerable)?
-
(o.GetType().IsGenericType && o is IList)怎么样 -
你真正想要完成什么?
-
您在寻找
o.GetType().GetGenericArguments()吗?