C# 投射整个数组? [英] C# Cast Entire Array?
问题描述
我看到了这个 Array.ConvertAll
方法,但它需要一个 Converter
作为参数.我不明白为什么我需要一个转换器,因为我已经在我的类中定义了一个隐式转换器:
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
数组.有没有很好的方法来做到这一点?或者我应该把它吸干并编写(另一个)转换器或循环遍历元素?
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 解决方案使用 Cast
/'Select' 很好,但既然你知道你在这里使用数组,使用ConvertAll
效率更高,而且同样简单.
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
意味着
a) 数组只迭代一次,
b) 对数组的操作更加优化(不使用IEnumerator
).
不要让 Converter
类型混淆你 - 它只是一个简单的委托,因此你可以为它传递一个 lambda 表达式,如上所示.
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屋!