我有一个包含一些变量的类:
public class Species
{
public string speciesName;
public string speciesEng;
public int modHappiness;
public int modSatiety;
public int modHydration;
public int modCommunication;
public int modVigor;
public int modCleanliness;
public Species(string speciesName, string speciesEng, int modHappiness, int modSatiety, int modHydration, int modCommunication, int modVigor, int modCleanliness)
{
this.speciesName = speciesName;
this.speciesEng = speciesEng;
this.modHappiness = modHappiness;
this.modSatiety = modSatiety;
this.modHydration = modHydration;
this.modCommunication = modCommunication;
this.modVigor = modVigor;
this.modCleanliness = modCleanliness;
}
}
我还有这个类的一些实例:
Species germanShepherd = new Species("Немецкая овчарка", "germanShepherd", 0, 0, 0, 0, 0, 0);
关闭程序后,有关宠物的数据保存到文本文件中:
public bool WriteToFile()
{
try
{
StreamWriter sw = new StreamWriter(name + ".data", false);
sw.WriteLine(name);
sw.WriteLine(species.speciesEng);
sw.WriteLine(gender);
sw.WriteLine(happiness);
sw.WriteLine(satiety);
sw.WriteLine(hydration);
sw.WriteLine(communication);
sw.WriteLine(vigor);
sw.WriteLine(cleanliness);
sw.WriteLine(trait.traitEng);
sw.WriteLine(ageMinutes);
for (int i = 0; i < inventory.Count; i++)
{
sw.WriteLine(inventory[i].itemEng);
sw.WriteLine(inventory[i].count);
}
for (int i = 0; i < effects.Count; i++)
{
sw.WriteLine(effects[i].effectEng);
}
sw.Close();
MessageBox.Show("Запись выполнена!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
return true;
}
catch
{
MessageBox.Show("Ошибка при записи!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
}
保存文件的样子:
Пёс
germanShepherd
Мужской
498500
9500
9500
10000
8750
10000
lazy
0
item1
1
item2
2
item3
3
sick
poisoned
问题是当我尝试将其加载到构造函数内的程序中时,我收到错误 CS0029“无法将字符串转换为 [ClassName]” 构造者:
public Pet(string filePath)
{
try
{
StreamReader sr = new StreamReader(filePath);
name = sr.ReadLine();
species = sr.ReadLine();
gender = sr.ReadLine();
happiness = int.Parse(sr.ReadLine());
satiety = int.Parse(sr.ReadLine());
hydration = int.Parse(sr.ReadLine());
communication = int.Parse(sr.ReadLine());
vigor = int.Parse(sr.ReadLine());
cleanliness = int.Parse(sr.ReadLine());
ageMinutes = int.Parse(sr.ReadLine());
trait = sr.ReadLine();
}
catch
{
throw new Exception("Ошибка чтения сохранения");
}
}
如何将字符串转换为类的现有实例?
我尝试过显式转换,但错误仍然存在:
species = (Species)sr.ReadLine();
UPD:“宠物”课程全貌:
public class Pet
{
public string name;
public Species species;
public string gender;
public int happiness;
public int satiety;
public int hydration;
public int communication;
public int vigor;
public int cleanliness;
public Traits trait;
public int ageMinutes;
public List<Items> inventory;
public List<Effect> effects;
/// <summary>
/// Конструктор нового питомца
/// </summary>
/// <param name="name">Имя питомца</param>
/// <param name="species">Вид питомца</param>
/// <param name="gender">Пол питомца</param>
/// <param name="trait">Черта питомца</param>
public Pet(string name, Species species, string gender, Traits trait)
{
this.name = name;
this.species = species;
this.gender = gender;
happiness = 500000;
satiety = 10000;
hydration = 10000;
communication = 10000;
vigor = 10000;
cleanliness = 10000;
ageMinutes = 0;
this.trait = trait;
inventory = new List<Items>();
effects = new List<Effect>();
}
public Pet(string filePath)
{
try
{
StreamReader sr = new StreamReader(filePath);
name = sr.ReadLine();
species = (Species)Activator.CreateInstance(null, sr.ReadLine());
gender = sr.ReadLine();
happiness = int.Parse(sr.ReadLine());
satiety = int.Parse(sr.ReadLine());
hydration = int.Parse(sr.ReadLine());
communication = int.Parse(sr.ReadLine());
vigor = int.Parse(sr.ReadLine());
cleanliness = int.Parse(sr.ReadLine());
ageMinutes = int.Parse(sr.ReadLine());
trait = sr.ReadLine();
}
catch
{
throw new Exception("Ошибка чтения сохранения");
}
}
/// <summary>
/// Метод записи нового \ перезаписи существующего файла сохранения питомца
/// </summary>
/// <returns>Удалось ли сохранить данные</returns>
public bool WriteToFile()
{
try
{
StreamWriter sw = new StreamWriter(name + ".data", false);
sw.WriteLine(name);
sw.WriteLine(species.speciesEng);
sw.WriteLine(gender);
sw.WriteLine(happiness);
sw.WriteLine(satiety);
sw.WriteLine(hydration);
sw.WriteLine(communication);
sw.WriteLine(vigor);
sw.WriteLine(cleanliness);
sw.WriteLine(trait.traitEng);
sw.WriteLine(ageMinutes);
for (int i = 0; i < inventory.Count; i++)
{
sw.WriteLine(inventory[i].itemEng);
sw.WriteLine(inventory[i].count);
}
for (int i = 0; i < effects.Count; i++)
{
sw.WriteLine(effects[i].effectEng);
}
sw.Close();
MessageBox.Show("Запись выполнена!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
return true;
}
catch
{
MessageBox.Show("Ошибка при записи!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
}
public void AssignItem(Items item) => inventory.Add(item);
public void AssignEffect(Effect effect)
{
effects.Add(effect);
happiness += effect.modHappiness;
satiety += effect.modSatiety;
hydration += effect.modHydration;
communication += effect.modCommunication;
vigor += effect.modVigor;
cleanliness += effect.modCleanliness;
}
public void RemoveEffect(Effect effect)
{
effects.Remove(effect);
happiness -= effect.modHappiness;
satiety -= effect.modSatiety;
hydration -= effect.modHydration;
communication -= effect.modCommunication;
vigor -= effect.modVigor;
cleanliness -= effect.modCleanliness;
}
public void StarveTick()
{
}
}
您最初的问题是尝试将文件中的字符串直接分配给 Species 类的实例,导致类型不匹配。要从字符串创建 Species 实例,我们需要实现逻辑以根据从文件读取的数据构造 Species 对象。
我觉得你的代码也有几个设计问题,所以我建议你在代码中遵循这些问题。
使用工厂模式从字符串创建 Species 对象。 将物种创建逻辑集中在 SpeciesFactory 类中。
通过允许轻松扩展以添加新物种定义(可能来自 JSON 文件)来提高可维护性。
public class Species
{
public string speciesName;
public string speciesEng;
public int modHappiness;
public int modSatiety;
public int modHydration;
public int modCommunication;
public int modVigor;
public int modCleanliness;
public Species(string speciesName, string speciesEng, int modHappiness, int modSatiety, int modHydration, int modCommunication, int modVigor, int modCleanliness)
{
this.speciesName = speciesName;
this.speciesEng = speciesEng;
this.modHappiness = modHappiness;
this.modSatiety = modSatiety;
this.modHydration = modHydration;
this.modCommunication = modCommunication;
this.modVigor = modVigor;
this.modCleanliness = modCleanliness;
}
}
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
public static class SpeciesFactory
{
private static Dictionary<string, Species> speciesDictionary;
static SpeciesFactory()
{
// Initialize the species from JSON or hardcoded values
LoadSpeciesFromJson("species.json"); // Optional JSON loading
}
private static void LoadSpeciesFromJson(string filePath)
{
if (File.Exists(filePath))
{
var json = File.ReadAllText(filePath);
var speciesList = JsonSerializer.Deserialize<List<Species>>(json);
speciesDictionary = speciesList?.ToDictionary(s => s.speciesEng)
?? new Dictionary<string, Species>();
}
else
{
// Fallback to hardcoded values if JSON file is missing
speciesDictionary = new Dictionary<string, Species>
{
{ "germanShepherd", new Species("Немецкая овчарка", "germanShepherd", 0, 0, 0, 0, 0, 0) },
{ "species2", new Species("Специес 2", "species2", 1, 1, 1, 1, 1, 1) }
// Add more species here...
};
}
}
public static Species CreateSpecies(string speciesEng)
{
if (speciesDictionary.TryGetValue(speciesEng, out Species species))
{
return species;
}
else
{
throw new ArgumentException($"Unknown species: {speciesEng}");
}
}
}
using System;
using System.IO;
public class Pet
{
private string name;
private Species species;
private string gender;
private int happiness;
private int satiety;
private int hydration;
private int communication;
private int vigor;
private int cleanliness;
private int ageMinutes;
private string trait;
public Pet(string filePath)
{
try
{
using (StreamReader sr = new StreamReader(filePath))
{
name = sr.ReadLine();
// Use SpeciesFactory to create the Species instance
string speciesEng = sr.ReadLine();
species = SpeciesFactory.CreateSpecies(speciesEng);
gender = sr.ReadLine();
happiness = int.Parse(sr.ReadLine());
satiety = int.Parse(sr.ReadLine());
hydration = int.Parse(sr.ReadLine());
communication = int.Parse(sr.ReadLine());
vigor = int.Parse(sr.ReadLine());
cleanliness = int.Parse(sr.ReadLine());
ageMinutes = int.Parse(sr.ReadLine());
trait = sr.ReadLine();
}
}
catch (Exception ex)
{
throw new Exception("Ошибка чтения сохранения: " + ex.Message);
}
}
}
//This optional JSON file (species.json) can be used to define species dynamically:
[
{
"speciesName": "Немецкая овчарка",
"speciesEng": "germanShepherd",
"modHappiness": 0,
"modSatiety": 0,
"modHydration": 0,
"modCommunication": 0,
"modVigor": 0,
"modCleanliness": 0
},
{
"speciesName": "Специес 2",
"speciesEng": "species2",
"modHappiness": 1,
"modSatiety": 1,
"modHydration": 1,
"modCommunication": 1,
"modVigor": 1,
"modCleanliness": 1
}
]
工厂模式:集中物种创建并提高可维护性。
错误处理:通过清晰的错误消息改进故障排除。
可扩展性:允许通过在 JSON 文件或硬编码字典中添加新物种来进行未来扩展。