简体   繁体   English

将任何类型的数组转换为List <T> (C#)

[英]Convert array of any type to List<T> (C#)

The function below accepts an object, which can sometimes be an array of a given type. 下面的函数接受一个对象,该对象有时可以是给定类型的数组。 In this case, I suppose the type could be determined with obj[0].GetType(), assuming the array has at least one member. 在这种情况下,我认为可以使用obj [0] .GetType()来确定类型,假设数组至少有一个成员。 I would like to convert such an array to a generic List<T> of appropriate type, but the code below only succeeds in converting to List<object>. 我想将这样的数组转换为适当类型的通用List <T>,但下面的代码只能成功转换为List <object>。 How can this be done? 如何才能做到这一点?

public object GetDeserializedObject(object obj, Type targetType)
        {
            if (obj is Array)
            {
                List<object> obj2 = new List<object>();
                for (int i = 0; i < ((Array)obj).Length; i++)
                {
                    obj2.Add(((object[])obj)[i]);
                }
                obj = obj2;
            }
            return obj;
        }

Note that GetSerializedObject() implements a function belonging to the IDataContractSurrogate interface, so I don't think I can change its signature as shown. 请注意,GetSerializedObject()实现了属于IDataContractSurrogate接口的函数,因此我认为我不能更改其签名,如图所示。

Assuming you don't know the type at compile-time, you'll want to create a generic method to do it, and then call it by reflection. 假设您在编译时不知道类型,您将需要创建一个通用方法来执行它,然后通过反射调用它。 For example: 例如:

private static List<T> ConvertArray<T>(Array input)
{
    return input.Cast<T>().ToList(); // Using LINQ for simplicity
}

public static object GetDeserializedObject(object obj, Type targetType)
{
    if (obj is Array)
    {
        MethodInfo convertMethod = typeof(...).GetMethod("ConvertArray",
            BindingFlags.NonPublic | BindingFlags.Static);
        MethodInfo generic = convertMethod.MakeGenericMethod(new[] {targetType});
        return generic.Invoke(null, new object[] { obj });
    }
    return obj;
}

(If you do know the type at compile-time, just make it a generic method and call Cast and ToList directly.) (如果知道在编译时的类型,只是让一个通用的方法,并呼吁CastToList直接。)

Try the Cast() Linq method: 试试Cast()Linq方法:

    public object GetDeserializedObject<T>(object obj)
    {
        if (obj is Array)
        {
            var list = ((Array)obj).Cast<T>().ToList();
            obj = list;
        }
        return obj;
    }

And you'll specify the type you want in T. 然后你将在T中指定你想要的类型。

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

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