2011-06-08 95 views
1

我目前正在尝试使用带泛型类型的扩展方法将IEnumerable<T>转换为T2类型的二维数组。您还应该能够选择要包含在该阵列中的T的哪些属性。通用类型扩展方法ToMultidimensionalArray

这是我走到这一步:

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。

任何输入将不胜感激。

谢谢,

丹尼斯

+0

这不起作用,因为T不知道任何特殊属性。 您定位哪个框架?任何机会使用动态(从.NET 4.0)? – user492238 2011-06-08 15:03:12

+0

已更新问题。我的确在使用4.0。 – 2011-06-08 15:04:13

回答

2

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

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的收藏品,其中这些对象具有T2性质类型。目标是获取每个对象的属性并将它们放置在多维数组中。如我错了请纠正我。

+0

有没有必要纠正你,因为你没有错,相反!感谢这个有用的答案。 – 2011-06-08 15:32:21

1

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

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

+0

是的,这也适用,谢谢! – 2011-06-08 15:32:35