简体   繁体   English

c#Reflection - 查找集合的通用类型

[英]c# Reflection - Find the Generic Type of a Collection

I'm reflecting a property 'Blah' its Type is ICollection 我正在反映一个属性'Blah',它的Type是ICollection

    public ICollection<string> Blah { get; set; }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var pi = GetType().GetProperty("Blah");
        MessageBox.Show(pi.PropertyType.ToString());
    }

This gives me (as you'd expect!) ICollection<string> ... 这给了我(正如你所期望的那样!) ICollection<string> ...

But really I want to get the collection type ie ICollection (rather than ICollection<string> ) - does anyone know how i'd do this please? 但实际上我想获得集合类型即ICollection (而不是ICollection<string> ) - 有谁知道我该怎么做呢?

You'll want to look at GetGenericTypeDefinition for example: 例如,您需要查看GetGenericTypeDefinition

   List<String> strings=new List<string>();


        Console.WriteLine(strings.GetType().GetGenericTypeDefinition());
        foreach (var t in strings.GetType().GetGenericArguments())
        {
            Console.WriteLine(t);

        }

This will output: 这将输出:

System.Collections.Generic.List`1[T] System.Collections.Generic.List`1 [T]
System.String System.String

您正在寻找GetGenericTypeDefinition方法:

MessageBox.Show(pi.PropertyType.GetGenericTypeDefinition().ToString());

I had a similar but much more complicated problem... I wanted to determine if a type is assignable to collection type members or array type members dynamically. 我有一个类似但更复杂的问题......我想确定一个类型是否可以动态分配给集合类型成员或数组类型成员。

So, here is better way how to get member type of collection or array dynamically with a validation if the type of an object to add is assignable to the collection or the array type members: 因此,如果要添加的对象的类型可分配给集合或数组类型成员,则有更好的方法如何通过验证动态获取成员类型的集合或数组:

        List<IComparable> main = new List<IComparable>() { "str", "řetězec" };
        IComparable[] main0 = new IComparable[] { "str", "řetězec" };
        IEnumerable collection = (IEnumerable)main;
        //IEnumerable collection = (IEnumerable)main0;
        string str = (string) main[0];
        if (collection.GetType().IsArray)
        {
            if (collection.GetType().GetElementType().IsAssignableFrom(str.GetType()))
            {
                MessageBox.Show("Type \"" + str.GetType() + "\" is ok!");
            }
            else
            {
                MessageBox.Show("Bad Collection Member Type");
            }
        }
        else
        {
            if (collection.GetType().GenericTypeArguments[0].IsAssignableFrom(str.GetType()))
            {
                MessageBox.Show("Type \"" + str.GetType() + "\" is ok!");
            }
            else
            {
                MessageBox.Show("Bad Collection Member Type");
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM