如何查找列表的成员类型 [英] How to find the member type of a list

查看:57
本文介绍了如何查找列表的成员类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我有这个:

So far I have this:

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));"行上崩溃.因为该数组为空,这意味着前一行无效.

but it crashes on the line "Type T = (Type)(typefield[0].GetValue(o));" because the array is empty, which means that the previous line did not work.

问题: 假设通过第一行的所有内容都是一个列表,那么我应该如何确定列表中对象的类型. (请注意,检查成员的类型还不够好.这些成员很可能是从列表定义中指定的Type派生的.)

Question: Assuming that everything that passes the first line is a List, how should I determine the type of objects in the list. (note that checking the type of the members is not good enough. The members are likely to be derived from the Type that is specified in the list definition.)

PS 我在这里读到,第一行是确定某些内容为列表的最佳方法: 如果对象是通用列表 您有更准确的方法吗?

P.S. I read here that my first line is the best way to determine something as a list: If object is Generic List Do you have a more accurate way?

推荐答案

我认为一个答案可能是这种方法:

I think one answer could be this method:

public IEnumerable<Type> GetGenericIEnumerables(object o) {
    return o.GetType()
            .GetInterfaces()
            .Where(t => t.IsGenericType == true
                && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            .Select(t => t.GetGenericArguments()[0])
            .ToList();
}

您可以通过以下方式使用它:

The you can use it this way:

var type= GetGenericIEnumerables(o).FirstOrDefault();

如果o不是IEnumerable<T>,则类型为null,否则返回T.

If o is is not IEnumerable<T>, then the type is null, else, it returns T.

当o不是通用的并且继承自IEnumerable<T>时(例如对于string),该函数将返回char.

It also works perfect when o is not generic itself, and inherits from IEnumerable<T>, for example for string the function will return char.

基于杰森的进攻.

这篇关于如何查找列表的成员类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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