C# 使用静态类和重写值
我正在从一个文件中读取宠物列表,我有一个简单的文本文件,它的每个属性都有一个新行。它通读我的第一个宠物完美,并使用我的字典来创建宠物。然而,当它清除这两个列表时,它会清除第一个创建的宠物的详细信息,当它们被读入第二个宠物时,它们最终会拥有匹配的特征,而我的所有8只宠物也是如此。我知道当我清除我的列表时,它会清除我以前创建的宠物的列表,但是为什么它不在名称上写上呢?我是OOP新手,所以如果我听起来完全不称职,请原谅我C# 使用静态类和重写值,c#,static,C#,Static,我正在从一个文件中读取宠物列表,我有一个简单的文本文件,它的每个属性都有一个新行。它通读我的第一个宠物完美,并使用我的字典来创建宠物。然而,当它清除这两个列表时,它会清除第一个创建的宠物的详细信息,当它们被读入第二个宠物时,它们最终会拥有匹配的特征,而我的所有8只宠物也是如此。我知道当我清除我的列表时,它会清除我以前创建的宠物的列表,但是为什么它不在名称上写上呢?我是OOP新手,所以如果我听起来完全不称职,请原谅我 public static List<Pet> LoadPetDet
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;
}
公共静态列表LoadPetDetails(字符串文件名)
{
登记组(“绵羊”,类型(绵羊));
登记组(“狗”,类型(狗));
寄存器集(“Cat”,类型(Cat));
注册集(“兔子”,类型(兔子));
StreamReader=新的StreamReader(文件名);
字符串种类、名称、id、品种、描述;
智力年龄;
布尔性别;
宠物大小;
List petTraits=新列表();
List require=新列表();
List loadedPets=新列表();
尝试
{
//读入当前有多少宠物在接受护理
int count=Convert.ToInt32(reader.ReadLine());
//阅读宠物1的详细信息,直到达到计数
对于(int j=1;jCreatePet中的某个地方,您可能有一些代码,如pet.Traits=petTraits;
。您正在将对相同列表的引用传递给您的函数创建的所有宠物。有两种方法可以解决此问题,简单的方法是在CreatePet()中创建一个列表副本,如pet.Traits=petTraits.ToList();
更好的解决方案是声明所有临时变量(种类、名称、petTraits等)在for循环中。在C中,您更喜欢让变量在尽可能短的生命周期内保持不变。避免这样的错误比重用变量带来的微小性能优势更重要。非常感谢!没错,我已经更改了变量名称,并将其移到了我的循环中以确保!projec明天到期,我现在才发现问题,非常感谢您的及时帮助!