如何解决C#

时间:2019-01-27 05:17:47

标签: c# class field

我正在学习教程,并试图解决遇到的这些错误消息中的挑战之一:

  

字段'Data.Age'从未分配,并且其默认值始终为0

     

“ Data.Month”字段从未分配,并且其默认值始终为空

代码运行良好,并且一切正常,但是我不知道此错误的确切含义(因为我为这些字段分配了内容)或解决方法。

我看着How to fix "Field X is never assigned to and will have its default value null"?,但不知道发生了什么。

class Program
{
    static void Main(string[] args)
    {
        var data = new Data();

        Console.WriteLine("What is your name?");
        data.Name = Console.ReadLine();

        while (data.Name == "")
        {
            data.Name = TryAgain();
        }

        Console.WriteLine("What is your age?");
        data.Age = int.Parse(Console.ReadLine());

        while (data.Age == null)
        {
            data.Age = int.Parse(TryAgain());
        }

        Console.WriteLine("What month were you born in?");
        data.Month = Console.ReadLine();

        while (data.Month == "")
        {
            data.Month = TryAgain();
        }

        Console.WriteLine("Your name is: {0}", data.Name);
        Console.WriteLine("Your age is: {0}", data.Age);
        Console.WriteLine("Your birth month is: {0}", data.Month);

    }

    static string TryAgain()
    {
        Console.WriteLine("You didn't type anything, please try again:");
        return Console.ReadLine();
    }
}

class Data
{
    public string Name;
    public int? Age;
    public string Month;
}

0 个答案:

没有答案