簡體   English   中英

將對象強制轉換為C#

[英]cast object to class C#

試圖將.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)對象”不工作...

謝謝

感謝您提供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,move和所有其他成員都是公開的,或者至少公開可以以其他方式進行修改。

另外你必須確保這一點

class TargetObj{}
class Cell{}

也標記為Serializable,否則它們將不會寫入文件,也不會有任何關於它們的反序列化信息。

編輯

在這里,您可以找到Unity支持的所有可序列化類型:

Unity SerializeField

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM