转换类型T的数组类型为我的数组,其中T实现了我在C# [英] Converting an array of type T to an array of type I where T implements I in C#
问题描述
我试图实现在C#中的东西,我用Java做容易。但遇到了一些麻烦。
我有类型T的对象数组的一个未定义的数
一个实现一个接口I.
我需要是所有值从所有阵列的总和末端我的阵列。
假设没有阵列将包含相同的值。
I am trying to accomplish something in C# that I do easily in Java. But having some trouble. I have an undefined number of arrays of objects of type T. A implements an interface I. I need an array of I at the end that is the sum of all values from all the arrays. Assume no arrays will contain the same values.
本的Java code ++工程。
This Java code works.
ArrayList<I> list = new ArrayList<I>();
for (Iterator<T[]> iterator = arrays.iterator(); iterator.hasNext();) {
T[] arrayOfA = iterator.next();
//Works like a charm
list.addAll(Arrays.asList(arrayOfA));
}
return list.toArray(new T[list.size()]);
然而,这C#code不:
However this C# code doesn't:
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
//Problem with this
list.AddRange(new List<T>(arrayOfA));
//Also doesn't work
list.AddRange(new List<I>(arrayOfA));
}
return list.ToArray();
所以,很明显我需要以某种方式获得的阵列 T []
到的IEnumerable&LT; I&GT;
来添加到列表中,但我不知道这样做的最佳方式?有什么建议?
So it's obvious I need to somehow get the array of T[]
into an IEnumerable<I>
to add to the list but I'm not sure the best way to do this? Any suggestions?
编辑:在VS 2008中开发,但需要编译.NET 2.0。
Developing in VS 2008 but needs to compile for .NET 2.0.
推荐答案
这里的问题是,C#不支持的协方差(至少直到C#4.0,我认为)在泛型泛型类型,所以隐式转换将无法工作。
The issue here is that C# doesn't support co-variance (at least not until C# 4.0, I think) in generics so implicit conversions of generic types won't work.
您可以试试这个:
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
list.AddRange(Array.ConvertAll<T, I>(arrayOfA, t => (I)t));
}
return list.ToArray();
对于任何横跨这个问题strumbles并正在使用.NET 3.5,这是在做同样的事情,使用LINQ的一个稍微紧凑的方式。
For anyone that strumbles across this question and is using .NET 3.5, this is a slightly more compact way of doing the same thing, using Linq.
List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
list.AddRange(arrayOfA.Cast<I>());
}
return list.ToArray();
这篇关于转换类型T的数组类型为我的数组,其中T实现了我在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!