Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将对象强制转换为列表_C#_Reflection - Fatal编程技术网

C# 如何将对象强制转换为列表

C# 如何将对象强制转换为列表,c#,reflection,C#,Reflection,我有一个对象,它实际上是一个列表。我有一个字符串,元素类型是什么,但我不知道如何将对象强制转换为列表?下面是一些描述我的问题的代码 class Data { public int ID { get; set; } public List<double> Values { get; set; } } static void Main(string[] args) { Data d = new Data() { ID = 69, Values = new Lis

我有一个对象,它实际上是一个列表。我有一个字符串,元素类型是什么,但我不知道如何将对象强制转换为列表?下面是一些描述我的问题的代码

class Data
{
    public int ID { get; set; }
    public List<double> Values { get; set; }
}

static void Main(string[] args)
{
    Data d = new Data() { ID = 69, Values = new List<double>() };
    d.Values.Add(1.0);
    d.Values.Add(2.0);

    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Data));
    var propInfo = typeof(Data).GetProperties();

    foreach (var p in propInfo)
    {
        var Value = p.GetValue(d, null);
        var Type = p.PropertyType;

        if (Type.IsGenericType && Type.GetGenericTypeDefinition() == typeof(List<>))
        {
            // get the element type of a list
            var ElementType = Value.GetType().GetProperty("Item").PropertyType;

            // how to cast to List< "ElementType" > ???
        }
        else
        {
            types.Add( Type.FullName );
        }
    }
}

泛型和反射不能很好地发挥作用。您最好使用非通用的IList API:


然后你可以迭代、索引访问、添加、删除等等。

泛型和反射不能很好地发挥作用。您最好使用非通用的IList API:


然后,您可以进行迭代、按索引访问、添加、删除等操作。

您打算如何处理它?强制转换到动态获取的类型列表似乎有点毫无意义,因为您的静态代码无法使用此附加类型信息。如果您希望以列表的形式访问数据,我建议强制转换到System.Collections.IList。您打算如何处理它?强制转换到动态获取的类型列表似乎有点毫无意义,因为您的静态代码无法使用此附加类型信息。如果您希望以列表的形式访问数据,我建议强制转换到System.Collections.IList。我只需要计数,但当我尝试您的方法时,我得到一个编译器错误,即IList需要1类型参数。我正在使用.NET4。我需要添加另一个命名空间吗?@chhenning是的,System.collections我只需要计数,但是当我尝试您的方法时,我得到一个编译器错误,说IList需要1类型的参数。我正在使用.NET4。是否需要添加另一个命名空间?@chhenning是,System.Collections
IList list = (IList)Value;