English 中文(简体)
C# Cast Entire Array?
原标题:C# Cast Entire Array?

参看<代码>Array.ConvertAll方法,但作为理由需要Converter<> >。 我看不出为什么我需要一名变换者,当时我已经把一个暗含的字句子定义为:

    public static implicit operator Vec2(PointF p)
    {
        return new Vec2(p.X, p.Y);
    }

页: 1 PointF to a range of Vec2s. 是否有这样做的 way? 或者,我是否只是uck,书写(另一)变换者或 lo倒分子?

最佳回答

使用<代码>Cast的拟议准则解决办法 选择是罚款,但因为你知道你正在这里使用<条码>,“一切<>/条码”与阵列一道工作,效率更高,而且简单。

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

纽约总部 大会和会议管理部印发 Converter<TInput, toutput> category confuse You - it is only a brief delegation, 因此,如上所示,你可以为此发表一个lam语。

问题回答

作为这一老问题的最新情况,你现在可以做:

myArray.Cast<Vec2>().ToArray();

我的Array载有源物体,Vec2是你想要投的类型。

Cast don t 认为用户有固定的转换,这样你就可以 like上这种阵列。 选择:

myArray.Select(p => (Vec2)p).ToArray();

或写一名兑换者:

Array.ConvertAll(points, (p => (Vec2)p));

由于事先知道结果的规模,后者可能更有效率。

最有效的方法是:

class A { };
class B : A { };

A[] a = new A[9];
B[] b = a as B[];

这是对@user366312询问的公费问题,而不是原始问题的答复。

联发援框架2.0的解决方案是什么?

据我所知,已经向全国扫盲和扫盲委员会介绍。 2007年数据网框架,版本3.5。 因此,这意味着不可能在“NET Framework 2.0”中使用LINQ。

因此,我只使用一种固定的排他性,并在阵列中吸收每个要素。

与此类似,无需测试:

var newArray = new NewType[myArray.Length];

for (var i = 0; i < myArray.Length; i++)
{
    newArray[i] = (NewType)myArray[i];
}

您可以采取如下方法:

public static NewType[] ConvertAll(Vec2[] myArray)
{
    var newArray = new NewType[myArray.Length];

    for (var i = 0; i < myArray.Length; i++)
    {
        newArray[i] = (NewType)myArray[i];
    }

    return newArray;
}

使用

var newArray = ConvertAll(myArray);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签