如何验证保存/加载系统的完整性



我正在用c#为一个大型游戏项目制作一个保存/加载系统。

每个必须保存的类实现了一个方法DoSnapshot()

在方法内部,程序员必须为类中的每个字段调用函数-如果foo应该保存,则DoSnapshot(foo),如果不应该保存,则Ignore(foo)

我有一个DoSnapshot方法用于许多基本类型,如DoFloat, DoString以及复杂类型的版本。

我有100个类和项目仍在开发中。

是否有可能添加某种验证,每个类中的所有字段都在Snapshot()Ignore()调用中使用?省略字段会导致bug。验证可以是运行时的,也可以是编译时的。我只想在开发过程中使用它,它不会发布给用户。

您可以向需要保存的字段添加一个属性,然后在DoSnapshot方法中循环遍历类中的每个属性。当属性具有您要查找的属性时,调用Snapshot,否则调用Ignore

public class SomeClass : SomeBaseClass
{
    [Required]
    public string Foo { get; set; }
    public string Bar { get; set; }
    public override void DoSnapshot()
    {
        var properties = this.GetType().GetProperties();
        foreach (var property in properties)
        {
            var isRequired = property.GetCustomAttributes(typeof (RequiredAttribute), false).Length > 0;
            if (isRequired)
            {
                // Something
            }
            else
            {
                // SomethingElse
            }
        }
    }
}

我要做的是创建一个属性和"标签"每个字段,如果它应该保存或不。然后,在运行时,我将使用反射查询类以获得应该序列化的所有字段:

public class RandomClass
{
    public string Foo { get; set; }
    [Ignore]
    public int Bar { get; set; }
}
public class IgnoreAttribute : Attribute
{
}
class Program
{
    static void Main(string[] args)
    {
        var properties = typeof(RandomClass).GetProperties()
                        .Where(prop => !prop.IsDefined(typeof(IgnoreAttribute), false));
        // Serialize all values
    }
}

最新更新