【问题标题】:Generic Type Extension Method ToMultidimensionalArray泛型类型扩展方法 ToMultidimensionalArray
【发布时间】:2011-06-08 14:59:56
【问题描述】:

我目前正在尝试使用泛型类型的扩展方法将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。

任何意见将不胜感激。

谢谢,

丹尼斯

【问题讨论】:

  • 这不起作用,因为 T 不知道任何特殊属性。你的目标是哪个框架?有机会使用动态(来自 .NET 4.0)吗?
  • 问题已更新。我确实在使用 4.0。

标签: c# arrays generics extension-methods ienumerable


【解决方案1】:

一般来说,这个问题可以用反射来解决:

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

我将问题理解为有一个Ts 集合,其中这些对象具有T2 类型的属性。目标是获取每个对象的属性并将它们放在一个多维数组中。如果我错了,请纠正我。

【讨论】:

  • 没有必要纠正你,因为你没有错,恰恰相反!感谢您提供这个有用的答案。
【解决方案2】:

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

但我不明白你想要什么。我认为这种方法行不通。

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多