You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中不使用if/else设置默认语言(English)的实现方法

在C#控制台程序中,用户未输入偏好语言时默认设置为English(不使用if/else)

你可以使用C#的**空合并运算符??**来实现需求,无需编写if/else语句。这个运算符会检查左侧表达式的返回值是否为null,若是则返回右侧的默认值,否则返回左侧的输入值。

修改后的完整代码如下:

using System;

namespace Practice1._3
{
    class Program
    {            
        static void Main(string[] args)
        {
            Console.WriteLine("What's your name:");
            string name = Console.ReadLine();
            Console.WriteLine("Age:");
            string Age = Console.ReadLine();
            Console.WriteLine("Preferred language:");
            // 使用空合并运算符设置默认语言
            string language = Console.ReadLine() ?? "English";


            Console.WriteLine("\n-----------------------------------------");
            Console.WriteLine("Your name is " + name);           
            Console.WriteLine("Your age is " + Age);
            Console.WriteLine("Your language is " + language);
        }
    }
}

说明

当用户在语言输入环节直接回车(未输入任何内容)时,Console.ReadLine()会返回null,此时??运算符会自动将language赋值为"English";如果用户输入了具体语言,就会直接使用用户输入的值。

内容的提问来源于stack exchange,提问作者user20814004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 13:05:19