簡體   English   中英

將任何類型的數組轉換為List <T> (C#)

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

下面的函數接受一個對象,該對象有時可以是給定類型的數組。 在這種情況下,我認為可以使用obj [0] .GetType()來確定類型,假設數組至少有一個成員。 我想將這樣的數組轉換為適當類型的通用List <T>,但下面的代碼只能成功轉換為List <object>。 如何才能做到這一點?

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

請注意,GetSerializedObject()實現了屬於IDataContractSurrogate接口的函數,因此我認為我不能更改其簽名,如圖所示。

假設您在編譯時不知道類型,您將需要創建一個通用方法來執行它,然后通過反射調用它。 例如:

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

(如果知道在編譯時的類型,只是讓一個通用的方法,並呼吁CastToList直接。)

試試Cast()Linq方法:

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

然后你將在T中指定你想要的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM