【问题标题】:c# Reflection - Find the Generic Type of a Collectionc# Reflection - 查找集合的泛型类型
【发布时间】:2011-02-03 09:37:45
【问题描述】:

我正在反映一个属性“Blah”,它的类型是 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());
    }

这给了我(如你所料!)ICollection&lt;string&gt; ...

但我真的想获得集合类型,即ICollection(而不是ICollection&lt;string&gt;)——有人知道我会怎么做吗?

【问题讨论】:

  • 但是它的类型 ICollection&lt;string&gt;...
  • 同意,ICollectionICollection&lt;T&gt; 是两种完全不同的类型。

标签: c# reflection properties types


【解决方案1】:

例如,您需要查看GetGenericTypeDefinition

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


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

        }

这将输出:

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

【讨论】:

  • +1 表示GetGenericArguments。这实际上就是我登陆这里时所寻找的。​​span>
【解决方案2】:

您正在寻找GetGenericTypeDefinition 方法:

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

【讨论】:

  • 请注意,这将返回“ICollection`1[T]”,这是 CLR 对“ICollection”的说法。我会提出相同的建议,所以 +1。
【解决方案3】:

我有一个类似但更复杂的问题...我想确定一个类型是否可以动态分配给集合类型成员或数组类型成员。

因此,如果要添加的对象的类型可分配给集合或数组类型成员,那么这是如何通过验证动态获取集合或数组的成员类型的更好方法:

        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");
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多