使用静态类和覆盖值

时间:2017-06-04 02:47:19

标签: c# static

我正在阅读一个文件中的宠物列表,我有一个简单的文本文件,它有一个新行的每个属性。它通过我的第一个宠物完美阅读,并使用我的字典创建宠物。然而,当它清除两个列表时,它会清除第一个创建的宠物的细节,当他们读入第二个宠物时,他们最终会有匹配的特征,这对我所有8只宠物都会继续。我知道当我清除我的清单时,它清除了我之前创建的宠物,但是为什么它也没有写出这个名字呢?我对OOP很新,所以如果我听起来完全无能,请原谅我。

public static List<Pet> LoadPetDetails(string filename)
    {
        RegisterPet("Sheep", typeof(Sheep));
        RegisterPet("Dog", typeof(Dog));
        RegisterPet("Cat", typeof(Cat));
        RegisterPet("Rabbit", typeof(Rabbit));

        StreamReader reader = new StreamReader(filename);
        string kind, name, id, breed, desc;
        int age;
        bool gender;
        petSize size;
        List<string> petTraits = new List<string>();
        List<string> require = new List<string>();
        List<Pet> loadedPets = new List<Pet>();

        try
        {
            //read in the count of how many pets in care currently
            int count = Convert.ToInt32(reader.ReadLine());

            //read in details for pet 1 through to we reach the count 
            for (int j = 1; j <= count; j++)
            {
                //clear both of these list from the previous pet
                petTraits.Clear();
                require.Clear();

                //read in the kind
                kind = reader.ReadLine();
                //read in name
                name = reader.ReadLine();
                //read in id
                id = reader.ReadLine();
                //read in the pet traits
                for (int i = 0; i <= 2; i++)
                    petTraits.Add(reader.ReadLine());
                //read in pet breed
                breed = reader.ReadLine();
                //read in the pet's description
                desc = reader.ReadLine();
                //read in list of requirments
                for (int i = 0; i <= 1; i++)
                    require.Add(reader.ReadLine());
                //read in age
                age = Convert.ToInt32(reader.ReadLine());
                //read in size
                size = ConvertToPetSize(reader.ReadLine());
                //read in gender
                gender = Convert.ToBoolean(reader.ReadLine());

                //create the pet and add it to the list of pets to return
                loadedPets.Add(Pet.CreatePet(kind, name, id, petTraits, breed, desc, require, age, size, gender));
            }
        }
        finally
        {
            reader.Close();
        }
        return loadedPets;
    }

1 个答案:

答案 0 :(得分:0)

在CreatePet的某个地方你可能有一些像pet.Traits = petTraits;这样的代码。您将对同一列表的引用传递给您的函数创建的所有宠物。有两种方法可以解决这个问题,简单的方法是在CreatePet() pet.Traits = petTraits.ToList();内创建一个副本,如#/bin/sh PLAN_VAR=$bamboo_my_plan_var echo "testing: $PLAN_VAR"

更好的解决方案是在for循环中声明所有临时变量(kind,name,petTraits等)。在C#中,您更喜欢在最短的生命周期范围内使用变量。避免这样的错误比重用变量的一些微小性能优势更重要。