将对象强制转换为C#类

3
尝试将.dat文件转换为其自身的类
  level0 = (Level0) LoadObjInBinary(level0, "Level" + levelNumber);

   public static object LoadObjInBinary(object myClass, string fileName) {
        fileName += ".dat";   
        if (File.Exists(FileLocation + fileName)) {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(FileLocation + fileName, FileMode.Open);
            myClass = bf.Deserialize(file);
            file.Close();
            return myClass;
        } else {
            return null;
        }
   }


Level() class

   [Serializable]
    public class Level0 { //Using this class to create Level.dat binary file 

        static int level = 1;
        static int moves = 15;
        static int seconds;
        static int minScoreForOneStar = 1000;
        static int minScoreForTwoStars = 1500;
        static int minScoreForThreeStars = 2000;

        static TargetObj[] targetObjs = {new TargetObj(Targets.Black, 10), new TargetObj(Targets.Freezer, 1), new TargetObj(Targets.Anchor, 2)}; 

        static Color[] colors = {Constants.grey, Constants.green, Constants.pink, Constants.brown, Constants.purple, Constants.lightBlue};

        static Cell[,] levelDesign;  

      //the rest is Properties of Fields

    }

问题:LoadObjInBinary返回null。文件路径正确,类也匹配,但不知道为什么"(Level0) object"不起作用...
谢谢

你也使用了BinaryFormatter来序列化Level0类型吗?只是为了验证路径是否正确,你能否将return null;替换为return new Level0(); - rene
1
仅返回翻译后的文本:文件未更改,存在并返回对象,但无法将其转换为Level0()。是的,我使用了BinaryFormatter进行序列化。 - MJakhongir
你能提供关于Level0类的额外信息吗?它被标记为可序列化吗?它是否包含其他自定义类型的成员? - Vect0rZ
是的,我编辑了我的问题,请检查。 - MJakhongir
1个回答

2
感谢您提供Level0课程。
问题在于静态字段永远不会被序列化,因为它们不属于您实例化的对象实例,而是全局的。
我假设您需要它们是静态的,以便它们可以从应用程序的所有部分访问,快速解决方法是创建另一个具有非静态成员的类,然后对其进行序列化-反序列化,并将其值分配给Level0的全局静态实例(无论您在何处使用它)。
[Serializable]
class Level0Data
{
    int level = 1;
    int moves = 15;
    int seconds;
    int minScoreForOneStar = 1000;
    ...
}

然后,经过序列化和反序列化之后,您可以执行以下操作。
 Level0Data deserializedObject = (Level0Data) LoadObjInBinary(..);
 Level0.level = deserializedObject.level;
 Level0.moves = deserializedObject.moves;

"你需要确保Level0.level、moves和所有其他成员都是公开的,或者至少以其他方式公开可修改。此外,你还需要确保..."
class TargetObj{}
class Cell{}

也要标记为Serializable,否则它们将不会被写入文件,也不会有关于它们的任何反序列化信息。
编辑
在这里,您可以找到Unity默认支持的所有可序列化类型:
Unity SerializeField。

1
非常感谢,它起作用了。我还添加了一个Color[],但它不可序列化,所以我将其更改为具有颜色十六进制值的string[]。 - MJakhongir
1
太好了!至于颜色,是的,我认为只有最新版本的Unity才支持其基元序列化。 - Vect0rZ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接