簡體   English   中英

泛型類型擴展方法 ToMultidimensionalArray

[英]Generic Type Extension Method ToMultidimensionalArray

我目前正在嘗試使用具有泛型類型的擴展方法將IEnumerable<T>轉換為 T2 類型的二維數組。 您還應該能夠選擇要包含在該數組中的 T 的哪些屬性。

這是我到目前為止得到的:

public static T2[][] ToMultidimensionalArray<T, T2>(this IEnumerable<T> enumerable, int count, params string[] propNames)
    {
        IEnumerator<T> enumerator = enumerable.GetEnumerator();
        T2[][] resultArray = new T2[count][];
        int i = 0;
        int arrLength = propNames.Length;
        while (enumerator.MoveNext())
        {
            resultArray[i] = new T2[arrLength];
            int j = 0;
            foreach(string prop in propNames)
            {
                resultArray[i][j] = ((T)enumerator.Current).//How do I access the properties?
                j++;
            }
            i++;
        }
        return resultArray;
    }

我在訪問foreach -Loop 中enumerator.Current的屬性時遇到問題。

我正在使用 .NET-Framework 4.0。

任何投入將不勝感激。

謝謝,

丹尼斯

一般來說,這個問題可以使用反射來解決:

public static T2[][] ToMultidimensionalArray<T, T2>(
                                                this IEnumerable<T> enumerable,
                                                int count,
                                                params string[] propNames)
{
    T2[][] resultArray = new T2[count][];
    int i = 0;
    int arrLength = propNames.Length;
    foreach (var item in enumerable)
    {
        resultArray[i] = new T2[arrLength];
        int j = 0;
        foreach (string prop in propNames)
        {
            // Get the required property info using reflection
            var propertyInfo = typeof(T).GetProperty(prop);
            // Extract the getter method of the property
            var getter = propertyInfo.GetGetMethod();
            // Invoke the getter and get the property value
            var value = getter.Invoke(item, null);
            // Cast the value to T2 and store in the array
            resultArray[i][j] = (T2) value;
            j++;
        }
        i++;
    }
    return resultArray;
}

我將問題理解為有一個T s 集合,其中這些對象具有T2類型的屬性。 目標是獲取每個 object 的屬性並將它們放入多維數組中。 如我錯了請糾正我。

你的意思是 (T2)typeof(T).GetProperty(prop).GetValue(enumerator.Current, null);

但我無法理解你想要什么。 我認為這種方法行不通。

暫無
暫無

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

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