0
我正在閱讀一個文件中的寵物列表,我有一個簡單的文本文件,並且每個屬性都有一個新行。它讀完我的第一隻寵物,並用我的字典創建寵物。然而,當清除兩個列表時,它清除了第一個創建的寵物的細節,並且當他們讀入第二個寵物時,它們最終具有匹配的特徵,並且這對我所有的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;
}
謝謝你這麼多!是的,就是這樣,我已經改變了變量名,並將其移入我的循環中以確保!項目明天到期,我現在才發現問題,非常感謝您的及時幫助! –