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

C#中能否在字符串内直接嵌入条件判断且不创建额外变量?

C#中直接在字符串内嵌入条件判断实现动态输出

当然可以,C#里有几种简洁的方式能做到,不需要创建额外变量:

  • 使用字符串插值+三元运算符(最常用的写法):
    直接在插值字符串里嵌入三元表达式,根据isEuropean的值动态拼接内容:

    bool isEuropean = true;
    Console.WriteLine($"This individual {(isEuropean ? "" : "not ")}is European");
    

    当isEuropean为true时,输出This individual is European;为false时输出This individual is not European。

  • 另一种写法(调整判断位置):
    如果习惯把判断放在"is"后面,也可以这么写:

    Console.WriteLine($"This individual is{(isEuropean ? "" : " not")} European");
    

    效果和上面完全一致,只是条件判断的位置不同,看个人编码习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:40:38