C# 投射整个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2068120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Cast Entire Array?
提问by mpen
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:
我看到了这个Array.ConvertAll
方法,但它需要 aConverter
作为参数。我不明白为什么我需要一个转换器,当我已经在我的班级中定义了一个隐式转换器时:
public static implicit operator Vec2(PointF p)
{
return new Vec2(p.X, p.Y);
}
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?
我正在尝试将PointF
s 数组转换为Vec2
s数组。有没有很好的方法来做到这一点?或者我应该把它吸起来并编写(另一个)转换器或循环遍历元素?
采纳答案by Noldorin
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.
建议的 LINQ 解决方案使用Cast
/'Select' 很好,但是由于您知道在这里使用数组,所以使用ConvertAll
更有效,而且同样简单。
var newArray = Array.ConvertAll(array, item => (NewType)item);
Using ConvertAll
means
a) the array is only iterated over once,
b) the operation is more optimised for arrays (does not use IEnumerator<T>
).
使用ConvertAll
意味着
a) 数组只迭代一次,
b) 操作对数组进行了更优化(不使用IEnumerator<T>
)。
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.
不要让Converter<TInput, TOutput>
类型混淆你——它只是一个简单的委托,因此你可以为它传递一个 lambda 表达式,如上所示。
回答by Mark Byers
Cast doesn't consider user defined implicit conversions so you can't cast the array like that. You can use select instead:
Cast 不考虑用户定义的隐式转换,因此您不能像这样转换数组。您可以使用 select 代替:
myArray.Select(p => (Vec2)p).ToArray();
Or write a converter:
或者写一个转换器:
Array.ConvertAll(points, (p => (Vec2)p));
The latter is probably more efficient as the size of the result is known in advance.
后者可能更有效,因为结果的大小是预先知道的。
回答by Ravi
As an update to this old question, you can now do:
作为对这个旧问题的更新,您现在可以执行以下操作:
myArray.Cast<Vec2>().ToArray();
where myArray contains the source objects, and Vec2 is the type you want to cast to.
其中 myArray 包含源对象,而 Vec2 是您要转换为的类型。
回答by fdafadf
The most efficient way is:
最有效的方法是:
class A { };
class B : A { };
A[] a = new A[9];
B[] b = a as B[];