c# Reflection - Find the Generic Type of a Collect

2019-04-18 15:31发布

I'm reflecting a property 'Blah' its Type is 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> ...

But really I want to get the collection type i.e. ICollection (rather than ICollection<string>) - does anyone know how i'd do this please?

3条回答
我想做一个坏孩纸
2楼-- · 2019-04-18 16:01

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");
            }
        }
查看更多
【Aperson】
3楼-- · 2019-04-18 16:03

You're looking for the GetGenericTypeDefinition method:

MessageBox.Show(pi.PropertyType.GetGenericTypeDefinition().ToString());
查看更多
劳资没心,怎么记你
4楼-- · 2019-04-18 16:23

You'll want to look at GetGenericTypeDefinition for example:

   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.String

查看更多
登录 后发表回答