C#铸造整个阵列? [英] C# Cast Entire Array?
问题描述
我看到这个 Array.ConvertAll
方法,但它需要一个转换
作为参数。我不明白为什么我需要一个转换器,当我已经定义在我班上一个隐含之一:
I see this Array.ConvertAll
method, but it requires a Converter
as an argument. I don't see why I need a converter, when I've already defined an implicit one in my class:
public static implicit operator Vec2(PointF p)
{
return new Vec2(p.X, p.Y);
}
我想投的PointF
所组成的阵列的 VEC2
秒的数组。有没有一个很好的办法做到这一点?或者我应该只是吮吸它和write(另一个)转换器或遍历所有的元素?
I'm trying to cast an array of PointF
s to an array of Vec2
s. Is there a nice way to do this? Or should I just suck it up and write (another) converter or loop over the elements?
推荐答案
使用建议的LINQ解决方案铸造
/'选择'是好的,但因为你知道你的工作这里有一个数组,使用 ConvertAll
是较为efficienct,只是简单。
The proposed LINQ solution using Cast
/'Select' is fine, but since you know you are working with an array here, using ConvertAll
is rather more efficienct, and just as simple.
var newArray = Array.ConvertAll(array, item => (NewType)item);
使用 ConvertAll
表示)的阵列只有遍历一次,不是两次,B)的操作数组更优化(不使用 IEnumerator的< T>
)
Using ConvertAll
means a) the array is only iterated over once, not twice, b) the operation is more optimised for arrays (does not use IEnumerator<T>
).
不要让转换器和LT; TInput,TOutput&GT;
键入迷惑你 - 它只是一个简单的委托,因此你可以传递一个Lambda前pression对于它,如上所示。
Don't let the Converter<TInput, TOutput>
type confuse you - it is just a simple delegate, and thus you can pass a lambda expression for it, as shown above.
这篇关于C#铸造整个阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!