反序列化文件时,无法从源类型强制转换为目标类型

本文关键字:类型 转换 目标 文件 反序列化 | 更新日期: 2023-09-27 18:22:03

我很难从两个独立的脚本中保存/读取文件,第一次在Unity中测试playerPrefs之外的文件保存/读取。我将文件保存在一个场景中,并尝试在另一个场景打开该文件。很明显,演员阵容有问题,但我不知道问题出在哪里。

以下是创建文件的代码:

using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class SubmitScript : MainScript {
[Serializable]
public class CardEntry {
    public int card_nr;
    public bool card_backFaceUp;
    public float card_posX;
    public float card_posY;
    public float card_posZ;
    public float card_rotZ;
}
public List<CardEntry> cardsList = new List<CardEntry>();
private GameObject cards_gameObject;

public void ReturnToSetupTemplatePanel () {
    // Set playerPref so the GameBoard is back to normal
    PlayerPrefs.SetString ("GameBoard Type","DoNormal");
    // Set playerPrefs so the Template panel is out
    PlayerPrefs.SetString ("PanelPosition", "TemplatePanel Visable");
    // Set info that there is an updated template file
    PlayerPrefs.SetString ("TemplateFile", "Exists");
    // Process the save operation
    CardEntry _cardEntry = new CardEntry ();
    _cardEntry.card_nr = 0;
    // Save all card objects properties
    foreach (GameObject aGO in master_GameObject_List) {
        cards_gameObject = GameObject.FindWithTag(aGO.tag);
        // Add the cards properties
        _cardEntry.card_nr++;
        if (cards_gameObject.tag.LastIndexOf ("B") != -1) { // Card have back face up
            _cardEntry.card_backFaceUp = false;
        }
        else {
            _cardEntry.card_backFaceUp = true;
        }
        _cardEntry.card_posX = aGO.transform.position.x;
        _cardEntry.card_posY = aGO.transform.position.y;
        _cardEntry.card_posZ = aGO.transform.position.z;
        _cardEntry.card_rotZ = aGO.transform.rotation.z;
        cardsList.Add(_cardEntry);
        print ("%: " + _cardEntry.card_nr + " % " + aGO.tag);
    }
    // Save card object data
    // Get binary formatter
    var b = new BinaryFormatter ();
    // Create a file
    var f = File.Create (Application.persistentDataPath + "/tempInfo.dat");
    // Save the scores
    b.Serialize (f, cardsList);
    f.Close ();
    // Go back to SetupScene
    Application.LoadLevel("SetupScene");
}
}

以下是我用来打开文件并尝试处理输出的代码:

using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class StartupScript : MonoBehaviour {
[Serializable]
public class CardEntry {
    public int card_nr;
    public bool card_backFaceUp;
    public float card_posX;
    public float card_posY;
    public float card_posZ;
    public float card_rotZ;
}
public List<CardEntry> cardsList2 = new List<CardEntry>();
private bool shouldPanelBeOut = false;
private string panelStatus;
public GameObject thePanel;
private string fileStatus;
public GameObject cards_gameObject;

void Start() {
    print ("Startup Script");
    // If needed
    //File.Delete (Application.persistentDataPath + "/tempInfo.dat");
    CardEntry _cardEntry = new CardEntry ();
    // Find out if the panel should be visable or not
    panelStatus = PlayerPrefs.GetString ("PanelPosition");// "TemplatePanel Visable"
    fileStatus = PlayerPrefs.GetString ("TemplateFile");
    if (panelStatus == "TemplatePanel Visable") {
        thePanel.GetComponent<RectTransform>().localPosition = new Vector3(0.0f, 0.0f, 0.0f);
        if (fileStatus == "Exists") {
            // If not blank then load it
            if (File.Exists (Application.persistentDataPath + "/tempInfo.dat")) {
                print ("File Exist");
                // Binary formatter for loading back
                var b = new BinaryFormatter();
                // Get the file
                var f = File.Open(Application.persistentDataPath + "/tempInfo.dat", FileMode.Open);
                // Load back the scores
                cardsList2 = (List<CardEntry>)b.Deserialize(f); //<<< CAST ERROR HERE
                f.Close();
            }
        }
        else {
            print("File does not Exist");
        }
    }
    print ("cardsList2.Count: " + cardsList2.Count);
}
}

铸造错误在这一行:

cardsList2 = (List<CardEntry>)b.Deserialize(f); //<<< CAST ERROR HERE

也存在文件

我已经测试了几个小时,但不知道问题出在哪里。

反序列化文件时,无法从源类型强制转换为目标类型

我遇到了同样的问题,我用一种简单的方法解决了它。

cardsList2 = b.Deserialize(f) as List<CardEntry>;

我认为,这将解决您的问题