C# &引用;指定的强制转换无效";连载

C# &引用;指定的强制转换无效";连载,c#,serialization,console,deserialization,C#,Serialization,Console,Deserialization,我正在做一个随机数学控制台项目,询问用户加法、减法、乘法、除法、幂和平方根问题 我试图让代码更复杂,告诉用户他们上次运行测试时得到的分数,并建议选择哪种难度 但是,当我运行代码时,我收到一个错误“指定的强制转换无效” 以下是发生错误的部分代码: [Serializable] public class ToFile { public int TotalScore { get; private set; } public int NumberOfQuestions { get; }

我正在做一个随机数学控制台项目,询问用户加法、减法、乘法、除法、幂和平方根问题

我试图让代码更复杂,告诉用户他们上次运行测试时得到的分数,并建议选择哪种难度

但是,当我运行代码时,我收到一个错误“指定的强制转换无效”

以下是发生错误的部分代码:

[Serializable]
public class ToFile
{
    public int TotalScore { get; private set; }
    public int NumberOfQuestions { get; }
    public UserDifficulty UserDifficulty { get; }
    public ToFile(int numberOfQuestions, UserDifficulty userDifficulty)
    {
        NumberOfQuestions = numberOfQuestions;
        UserDifficulty = userDifficulty;
    }
    public static void Serialize()
    {
        var (userDifficulty, numberOfQuestions) = UserInputs();
        ToFile obj = new ToFile(numberOfQuestions, userDifficulty);
        _ = obj.NumberOfQuestions;
        _ = obj.UserDifficulty;
        _ = obj.TotalScore;
        Stream stream = new FileStream("Example.txt", FileMode.Create, FileAccess.Write);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, obj);
        stream.Close();
    }
    public static void Deserialize()
    {
        Stream stream = new FileStream("Example.txt", FileMode.Open, FileAccess.Read);
        BinaryFormatter formatter = new BinaryFormatter();
        ToFile objnew = (ToFile)formatter.Deserialize(stream);
        stream.Close();
        Console.WriteLine($"Last time you did the test on {objnew.UserDifficulty} level and got {objnew.TotalScore}/{objnew.NumberOfQuestions}");

        double decimalScore = (double)objnew.TotalScore / (double)objnew.NumberOfQuestions;

        if (objnew.UserDifficulty == UserDifficulty.Easy)
        {
            if (decimalScore <= 0.7)
            {
                Console.WriteLine($"You should stay on Easy difficulty");
            }
            else
            {
                Console.WriteLine($"Easy difficulty seems to easy for you! You should go up to Normal difficulty");
            }
        }
        else if (objnew.UserDifficulty == UserDifficulty.Normal)
        {
            if (decimalScore <= 0.3)
            {
                Console.WriteLine($"Normal difficulty seems to be to hard for you:( You should go down to Easy difficulty");
            }
            else if ((decimalScore > 0.3) && (decimalScore <= 0.7))
            {
                Console.WriteLine($"You should stay on Normal difficulty");
            }
            else
            {
                Console.WriteLine($"Normal difficulty seems to easy for you! You should go up to Hard difficulty");
            }
        }
        else if (objnew.UserDifficulty == UserDifficulty.Hard)
        {
            if (decimalScore <= 0.3)
            {
                Console.WriteLine($"Hard difficulty seems to hard for you:( You should go down to Normal difficulty");
            }
            else if ((decimalScore > 0.3) && (decimalScore <= 0.8))
            {
                Console.WriteLine($"You should stay on Hard difficulty");
            }
            else
            {
                Console.WriteLine($"You are a maths Genius! Sadly this is the hardest level");
            }
        }
        Console.ReadKey();
        Console.Write(Environment.NewLine);
    }
}

public static void Main(string[] args)
    {
        ToFile.Deserialize();
        ToFile.Serialize();
    }
[可序列化]
公共类文件
{
公共整数TotalScore{get;私有集;}
公共整数问题{get;}
公共用户困难用户困难{get;}
公共ToFile(int numberOfQuestions,用户难度用户难度)
{
NumberOfQuestions=NumberOfQuestions;
用户难度=用户难度;
}
公共静态void Serialize()
{
var(用户难度,numberOfQuestions)=用户输入();
ToFile obj=新ToFile(问题数、用户难度);
_=obj.numberofproblems;
_=目标用户难度;
_=obj.TotalScore;
Stream=新文件流(“Example.txt”,FileMode.Create,FileAccess.Write);
BinaryFormatter formatter=新的BinaryFormatter();
序列化(流,obj);
stream.Close();
}
公共静态void反序列化()
{
Stream=新文件流(“Example.txt”,FileMode.Open,FileAccess.Read);
BinaryFormatter formatter=新的BinaryFormatter();
ToFile objnew=(ToFile)格式化程序。反序列化(流);
stream.Close();
WriteLine($“上次您在{objnew.usercombility}级别上进行测试并获得{objnew.TotalScore}/{objnew.NumberOfQuestions}”);
双小数分数=(双)objnew.TotalScore/(双)objnew.NumberOfQuestions;
if(objnew.userdemobility==userdemobility.Easy)
{
如果(小数点)
运行时出现错误“指定的强制转换无效”
代码

我从中尝试了您的代码,该代码对我有效。我怀疑您上次用户选择的文件
Examples.txt
包含无效数据,因此您在尝试对其中包含的数据进行反序列化时出错。请尝试删除该文件,然后重新创建它。我认为这将解决问题


我的代码现在运行了两次我的
UserInputs
函数。你能帮我吗 帮我修这个

问题是,您将其称为两次:

  • 第一次-在调用方法
    ToFile.Serialize
    之前在方法
    Main
    内部
  • 第二次-内部方法
    ToFile.Serialize
要解决此问题,应在
Main
中重写代码:

ToFile.Deserialize();
var (userDifficulty, numberOfQuestions) = UserInputs();
OperationQuestionScore score = RunTest(numberOfQuestions, userDifficulty);
// 1. You should serialize data after running a test, because property
//    ToFile.TotalScore can be filled only after test.
// 2. Now we pass into method Serialize three parameters: numberOfQuestions,
//    score.TotalScore and userDifficulty.
ToFile.Serialize(numberOfQuestions, score.TotalScore, userDifficulty);
并对
ToFile.Serialize
方法进行下一步更改:

public static void Serialize(int numberOfQuestions, int totalScore, UserDifficulty userDifficulty)
{
    // Now you can delete this line, because user input comes from method parameters.
    // var (userDifficulty, numberOfQuestions) = UserInputs();

    // And then serialize values: numberOfQuestions, totalScore, userDifficulty.
    ...
}

请阅读,并尝试在问题中包含代码片段,以及发生异常的信息。在
序列化()中,什么是
method?@vasily.sib这是一个丢弃的OK-在这种情况下,请使用JSON。我从github尝试了您的代码,它对我有效。只出现了一个问题。在
Main
方法中,您调用
ToFile.Deserialize()
不检查上次用户选择的文件是否存在。这会导致异常。在调用
ToFile.Deserialize()之前添加此检查
。我还建议您删除文件
Examples.txt
,并尝试重新创建该文件。其中的数据可能无效,因此您会生成错误。如果错误继续发生,请将堆栈跟踪附加到您的帖子中。@danyal51我为您的问题添加了答案。请检查这些问题。