C# Cast Entire Array?

前端 未结 4 1078
鱼传尺愫
鱼传尺愫 2020-11-30 09:43

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

相关标签:
4条回答
  • 2020-11-30 09:56

    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.

    0 讨论(0)
  • 2020-11-30 10:16

    Cast doesn't consider user defined implicit conversions so you can't cast the array like that. You can use select instead:

    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.

    0 讨论(0)
  • 2020-11-30 10:19

    The most efficient way is:

    class A { };
    class B : A { };
    
    A[] a = new A[9];
    B[] b = a as B[];
    
    0 讨论(0)
  • 2020-11-30 10:22

    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);
    

    Using ConvertAll means
    a) the array is only iterated over once,
    b) the operation is more optimised for arrays (does not use 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.

    0 讨论(0)
提交回复
热议问题