C# 投射整个数组? [英] C# Cast Entire Array?

查看:40
本文介绍了C# 投射整个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个 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 PointFs to an array of Vec2s. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆