Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

C# Array Copy from Utils.CopyArray, my source code won't convert

I am currently using this in my C# code:

numArray = (int[])Utils.CopyArray(numArray, new int[num3 + 1]);

I would like to switch to Array.Copy but can't figure out how without making errors (index out of range, etc).

UPDATED CODE TO SHOW MORE DEPTH

            var num3 = 0;
            int[] numArray = { };
            var mediafileName = @"";

            for (var j = 0; j <= PlayListGrid.Rows.Count - 1; j++)
            {
                if (!Equals(Convert.ToString(PlayListGrid.Rows[j].Cells["Song"].Value), @""))
                {
                    num3++;
                    numArray = (int[])Utils.CopyArray(numArray, new int[num3 + 1]);
                    numArray[num3] = j;
                }
                else
                {
                    mediafileName = Convert.ToString(PlayListGrid.Rows[j].Cells["MediaFileName"].Value);
                }

                table.Rows.Add((j + 1).ToString(), @"",
                    Convert.ToString(PlayListGrid.Rows[j].Cells["Artist"].Value),
                    Convert.ToString(PlayListGrid.Rows[j].Cells["Title"].Value),
                    Convert.ToString(PlayListGrid.Rows[j].Cells["DiscId"].Value),
                    mediafileName,
                    Convert.ToString(PlayListGrid.Rows[j].Cells["Time"].Value),
                    Convert.ToString(PlayListGrid.Rows[j].Cells["TimeLengthSecs"].Value));
            }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a solution that doesn't throw an exception, but returns false on failure. But I don't recommend it because, with exceptions, you can find and solve errors very well. I hope I understand the question right.

public static bool CopyArray<T>(ref T[] output, T[] arr) {
    try {
        T[] tmp = output;
        Array.Copy(tmp, arr);
        output = tmp;
        return true;
    catch {
        return false;
    }
}

Usage:

int num3 = 0; // your value
int[] numArray = null; // your value
CopyArray(ref numArray, new int[num3 + 1]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...