我是一个游戏助手(请参见http://haighshroom.blogspot.com了解更多信息),并使用XML文件保存/加载游戏。目前,每个类的保存格式都使用不同的结构体,但是继续更新保存文件结构变得繁琐,因此我想尝试采用以下通用方法。
假设我有3个类,它们都继承自BaseClass:
Class1,它有Property1、Property2(假设所有属性都是整数)
Class2,它有Property2、Property3
Class3,它有Property1、Property3
现在,我的新通用SaveStruct将如下所示:
我不知道如何定义以下部分:
- Exists(e.Property1) - 这需要使用反射来确定实例e是否已定义Property1(由于我们是从BaseClass调用,因此需要使用Reflection)。
- Get(e.Property1) - 如果Property1确实存在于实例e中,则需要获取它的值。
- Set(e.Property1 = es.Property1) - 如果实例e存在Property1,则需要设置其值。
非常感谢。
假设我有3个类,它们都继承自BaseClass:
Class1,它有Property1、Property2(假设所有属性都是整数)
Class2,它有Property2、Property3
Class3,它有Property1、Property3
现在,我的新通用SaveStruct将如下所示:
public struct EntityStruct
{
public string ClassName;
public int Property1;
public int Property2;
public int Property3;
public EntityStruct()
{
ClassName = "";
Property1 = Property2 = Property3 = 0;
}
}
当保存/加载特定实体时,我想要实现以下伪代码(两个函数都从BaseClass调用):
public EntityStruct GetSaveStruct()
{
EntityStruct es = new EntityStruct();
es.ClassName = this.GetType().Name;
if Exists(this.Property1) es.Property1 = Get(this.Property1);
if Exists(this.Property2) es.Property2 = Get(this.Property2);
if Exists(this.Property3) es.Property3 = Get(this.Property3);
}
public void LoadFromStruct(EntityStruct es)
{
BaseClass e = (BaseClass)(Activator.CreateInstance(null, GV.NameSpace + es.ClassName).Unwrap());
if Exists(e.Property1) Set(e.Property1 = es.Property1);
if Exists(e.Property2) Set(e.Property2 = es.Property2);
if Exists(e.Property3) Set(e.Property3 = es.Property3);
}
我不知道如何定义以下部分:
- Exists(e.Property1) - 这需要使用反射来确定实例e是否已定义Property1(由于我们是从BaseClass调用,因此需要使用Reflection)。
- Get(e.Property1) - 如果Property1确实存在于实例e中,则需要获取它的值。
- Set(e.Property1 = es.Property1) - 如果实例e存在Property1,则需要设置其值。
非常感谢。
var newObj = JsonConvert.DeserializeObject<SomeOtherClass>(JsonConvert.SerializeObject(yourObject));
- L.B