【问题标题】:C# get list from property and get it type [duplicate]C#从属性中获取列表并获取它类型[重复]
【发布时间】:2014-02-07 10:34:11
【问题描述】:

我需要获取一种列表元素。

using System;
using System.Collections;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        var xClass = new XClass();
        xClass.Do();
    }
}

public class XClass
{
    public List<string> list1 = new List<string>();

    public List<string> list2 { get; set; }

    public void Do()
    {
       // first
        Console.WriteLine("Type = {0}", GetListType(list1));

        // second
        var propertyList = this.GetType().GetProperty("list2"); // i get list from reflection

        // Create instance of list2
        var newList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(propertyList.PropertyType))); 

        Console.WriteLine("Type = {0}", GetListType(newList));
    }

    private Type GetListType(IEnumerable list)
    {
        return list.GetType().GetGenericArguments()[0];
    }
}

输出:

Type = System.String

Type = System.Collections.Generic.List`1[System.String]

第二种情况我需要获取“System.String”

你可以在这里测试代码http://ideone.com/uLkfBx

【问题讨论】:

  • newListList&lt;List&lt;string&gt;&gt; 是故意的吗?
  • 提示:propertyList.PropertyType 是什么?尝试输出它。通常,不要只是尝试将各个部分拼凑在一起,而是要思考代码的作用。众所周知,它有时会提供帮助。
  • 谢谢大家,我很笨:)

标签: c# list types


【解决方案1】:

语句var newList = (IList)Activator.CreateInstance((typeof(List&lt;&gt;).MakeGenericType(propertyList.PropertyType))); 创建一个包含list2 类型的泛型列表的实例。所以newListList&lt;List&lt;string&gt;&gt; 类型,因此你的结果是正确的。

【讨论】:

    猜你喜欢
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    相关资源
    最近更新 更多