为什么这样不对?QAQ

这样不对

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _6._5
{
    class Program
    {
        static void Main(string[] args)
        {
            int  dt = DateTime.Now.Month ;
            Console.WriteLine("您现在处于{0}月", dt);
            string w1 ;
            switch (dt)
            {
                case 12:
                case 1:
                case 2: w1 = "您现在处于冬季!"; break;
                case 3:
                case 4:
                case 5: w1 = "您现在处于春季!"; break;
                case 6 :
                case 7 :
                case 8: w1 = "您现在处于夏季!"; break;
                case 9 :
                case 10 :
                case 11: w1 = "您现在处于秋季"; break;
            }
            Console.WriteLine(w1);
            Console.ReadLine();
        }
    }
}

但是这样就对了。。。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _6._5
{
    class Program
    {
        static void Main(string[] args)
        {
            int  dt = DateTime.Now.Month ;
            Console.WriteLine("您现在处于{0}月", dt);
            string w1 ="";
            switch (dt)
            {
                case 12:
                case 1:
                case 2: w1 = "您现在处于冬季!"; break;
                case 3:
                case 4:
                case 5: w1 = "您现在处于春季!"; break;
                case 6 :
                case 7 :
                case 8: w1 = "您现在处于夏季!"; break;
                case 9 :
                case 10 :
                case 11: w1 = "您现在处于秋季"; break;
            }
            Console.WriteLine(w1);
            Console.ReadLine();
        }
    }
}

但是课本上明明就是第一种写法啊,我的报错,使用了未赋值的变量w1.。。。。。明明已经赋值。。。。QwQ

qq_守夜人_11
浏览 1413回答 2
2回答

慕仔0944135

你那个switch没default,也就是说如果没在那个范围直接跳出来,然后Console.WriteLine(w1)的时候会有w1没赋值的情况,编译器不允许吧。

笔墨遥仙

局部变量,要使用就必须先赋值!
打开App,查看更多内容
随时随地看视频慕课网APP