我的 Class 变量数组没有按预期工作的问题 - C#

Problem with My Class Variables Array is not working as intended - C#

提供一些背景信息。所以对于这个项目,我有一个 class 变量数组,即 cd1。这是 AudioCD 的变量,它是一个数组,因为如果用户想在数组中输入更多 CD。

我遇到的问题是,当我在 class 数组中输入多张 cd 时,在我添加字符串或艺术家的部分周围出现问题。当我去打印应该单独的 class 变量特定索引时,除了艺术家数组之外的大部分内容都显示最后输入的行出于某种奇怪的原因。我想弄清楚为什么要这样做。

PS。对不起,我的解释不是最好的。

如图所示。输出应该是当我输入 1 作为选择,1 作为 CD 时,数组应该使用索引 0 的数组,但它使用的是最后输入的 CD 中的数组。输出应该是:

man1 男人2 man3

但它是:

man4 男人5 man6

    class AudioCD
    {
        // Private Variables for CDclass 
        public string cdTitle { get; private set; }
        private string[] artists = new string[4];
        public int releaseYear { get; private set; }
        public string genre { get; private set; }
        public float condition { get; private set; }

        // Constructor for the CDclass - initializes all variables used in the CDclass
        public AudioCD()
        {
            cdTitle = "";
            artists = new string[] {"","","",""};
            releaseYear = 1980;
            genre = "";
            condition = 0.0f;
        }

        // Overload Constructor for the CDclass - initializes all the variables to user input variables
        public AudioCD(string cdt, string[] art, int reY, string gen, float con)
        {
            
            cdTitle = cdt;

            if (artists.Length < art.Length)
            {
                Console.WriteLine("Your Array size is bigger then 4 for the Artist so the first 4 names will be used!");
            }
            artists = art;

            if (reY < 1980)
            {
                releaseYear = 1980;
            }
            else
            {
                releaseYear = reY;
            }
            genre = gen;
            if (con < 0.0f || con > 5.0f)
            {
                condition = 0.0f;
            }
            else
            {
                condition = con;
            }
        }

        public void printAudioCD()
        {
            Console.Write(cdTitle + ", " + releaseYear + "\n" );
            for (int i = 0; i < artists.Length; i++)
            {
                if (artists[i] != "" )
                {
                    Console.WriteLine("Artist (#" + (i + 1) + "): " + artists[i]);
                }
            }
            Console.WriteLine("Genre: " + genre);
            Console.WriteLine("Condition: " + condition);

        }

    }

Program class:

class Program
{
    static void Main(string[] args)
    {
        // variables
        string uI, cdtitle, genre;
        int size = 0, releaseYear, choice, arrInd;
        string[] artistArray = new string[4] {"", "", "", "" };
        float condition;

        //
        AudioCD remote = new AudioCD();

        Console.Write("How many CDs do you have lying around your car? ");
        uI = Console.ReadLine();
        size = Convert.ToInt32(uI);

        AudioCD[] cd1 = new AudioCD[size];

        for (int i = 0; i < size; i++)
        {
            Console.WriteLine("CD #" + (i + 1));
            Console.Write("*Enter Title: ");
            uI = Console.ReadLine();
            cdtitle = uI;

            Console.WriteLine("*Enter Artists (type -1 when finished):");
             int j = 0;
            do
            {
                uI = Console.ReadLine();
                if (uI != "-1")
                    artistArray[j] = uI;
                j++;

                // Resize the array by One Element
                if (j >= 4 && uI != "-1")
                {
                    Array.Resize(ref artistArray, artistArray.Length + 1);
                    artistArray[j] = "";
                }

            } while (uI != "-1" );

            Console.Write("*Enter Genre: ");
            uI = Console.ReadLine();
            genre = uI;

            Console.Write("*Enter Release Year: ");
            uI = Console.ReadLine();
            releaseYear = Convert.ToInt32(uI);

            Console.Write("*Enter Condition: ");
            uI = Console.ReadLine();
            condition = float.Parse(uI);

            Console.Write("\n");

            // switch to select which class of cd to put information in
            cd1[i] = new AudioCD(cdtitle, artistArray, releaseYear, genre, condition);
            

        }

        bool isPlaying = true;

        while(isPlaying)
        {
            Console.Write("\n");
            Console.WriteLine("[Main Menu]");
            Console.WriteLine("1) Album Info");
            Console.WriteLine("2) Find a CD");
            Console.WriteLine("3) Find an artist");
            Console.WriteLine("4) Log off");
            Console.Write("Choice: ");
            uI = Console.ReadLine();
            choice = Convert.ToInt32(uI);

            switch(choice)
            {
                case 1:
                    {
                        Console.Write("\nWhich CD do you want? ");
                        uI = Console.ReadLine();
                        arrInd = Convert.ToInt32(uI);

                        if (arrInd >= 1 || arrInd <= size)
                        {
                            Console.Write(arrInd + ". ");
                            cd1[(arrInd - 1)].printAudioCD();
                        }

                        break;
                    }
                case 2:
                    {
                        break;
                    }
                case 3:
                    {
                        break;
                    }
                case 4:
                    {
                        isPlaying = false;
                        break;
                    }
                default:
                    {
                        break;
                    }
            }


        }
    }
}

输出 正如您在 image 中看到的那样。输出应该是当我输入 1 作为选择,1 作为 CD 时,数组应该使用索引 0 的数组,但它使用的是最后输入的 CD 中的数组。输出应该是man1、man2、man3,结果是man4、man5、man6。

您在 Main() 中每次迭代都使用相同的数组,这就是您从最后输入的 CD 中获取艺术家的原因。我的意思是这个代码片段:

string[] artistArray = new string[4] {"", "", "", "" };

这里我们可以使用List<T>来避免编写调整数组大小的代码,我们可以使用Clear()方法来避免存储以前CD中的艺术家。

整个代码如下所示。我使用 List:

稍微重构了您的代码

class AudioCD:

public class AudioCD
{
    // Private Variables for CDclass 
    public string cdTitle { get; private set; }

    private List<string> artists = new List<string>();
    public int releaseYear { get; private set; }
    public string genre { get; private set; }
    public float condition { get; private set; }

    // Constructor for the CDclass - initializes all variables used in the CDclass
    public AudioCD()
    {
        cdTitle = "";
        releaseYear = 1980;
        genre = "";
        condition = 0.0f;
    }

    // Overload Constructor for the CDclass - initializes all the variables to user input variables
    public AudioCD(string cdt, List<string> art, int reY, string gen, float con)
    {

        cdTitle = cdt;

        artists.AddRange(art);

        if (reY < 1980)
        {
            releaseYear = 1980;
        }
        else
        {
            releaseYear = reY;
        }
        genre = gen;
        if (con < 0.0f || con > 5.0f)
        {
            condition = 0.0f;
        }
        else
        {
            condition = con;
        }
    }

    public void printAudioCD()
    {
        Console.Write(cdTitle + ", " + releaseYear + "\n");
        for (int i = 0; i < artists.Count; i++)
        {
            if (artists[i] != "")
            {
                Console.WriteLine("Artist (#" + (i + 1) + "): " + artists[i]);
            }
        }
        Console.WriteLine("Genre: " + genre);
        Console.WriteLine("Condition: " + condition);
    }
}

Main 方法如下所示:

// variables
string uI, cdtitle, genre;
int size = 0, releaseYear, choice, arrInd;
List<string> artistArray = new List<string>();
float condition;

Console.Write("How many CDs do you have lying around your car? ");
uI = Console.ReadLine();
size = Convert.ToInt32(uI);

AudioCD[] cd1 = new AudioCD[size];

for (int i = 0; i < size; i++)
{
    Console.WriteLine("CD #" + (i + 1));
    Console.Write("*Enter Title: ");
    uI = Console.ReadLine();
    cdtitle = uI;

    Console.WriteLine("*Enter Artists (type -1 when finished):");
    int j = 0;
    do
    {
        uI = Console.ReadLine();
        if (uI != "-1")
            artistArray[j] = uI;
        j++;

    } while (uI != "-1");

    Console.Write("*Enter Genre: ");
    uI = Console.ReadLine();
    genre = uI;

    Console.Write("*Enter Release Year: ");
    uI = Console.ReadLine();
    releaseYear = Convert.ToInt32(uI);

    Console.Write("*Enter Condition: ");
    uI = Console.ReadLine();
    condition = float.Parse(uI);

    Console.Write("\n");

    // switch to select which class of cd to put information in
    cd1[i] = new AudioCD(cdtitle, artistArray, releaseYear, genre, condition);

    artistArray.Clear();
}

bool isPlaying = true;

while (isPlaying)
{
    Console.Write("\n");
    Console.WriteLine("[Main Menu]");
    Console.WriteLine("1) Album Info");
    Console.WriteLine("2) Find a CD");
    Console.WriteLine("3) Find an artist");
    Console.WriteLine("4) Log off");
    Console.Write("Choice: ");
    uI = Console.ReadLine();
    choice = Convert.ToInt32(uI);

    switch (choice)
    {
        case 1:
            {
                Console.Write("\nWhich CD do you want? ");
                uI = Console.ReadLine();
                arrInd = Convert.ToInt32(uI);

                if (arrInd >= 1 || arrInd <= size)
                {
                    Console.Write(arrInd + ". ");
                    cd1[(arrInd - 1)].printAudioCD();
                }

                break;
            }
        case 2:
            {
                break;
            }
        case 3:
            {
                break;
            }
        case 4:
            {
                isPlaying = false;
                break;
            }
        default:
            {
                break;
            }
    }
}