【问题标题】:Condition within string definition字符串定义中的条件
【发布时间】:2021-12-09 04:12:01
【问题描述】:

我曾经写过这个

if (condition)
{
    str = "A";
}
else
{
    str = "B";
}

finalstr = "Hello "+str;

不知道有没有更好的办法。

我想要的是

finalstr = "Hello "+ if (condition) {str = "A"} else {str = "B"};

finalstr = "Hello "+ condition ? "A" : "B";

类似$var = "Hello ".if(condition)... 在 php 中。

是否有类似的方法可以将条件直接放入字符串中?

【问题讨论】:

  • 你在那里——这只是一个优先问题。 finalstr = "Hello " + (condition ? "A" : "B");
  • 你在找string interpolationfinalstr = $"Hello { (condition ? "A" : "B") }";
  • @DM 示例是使用字符串的正确方法,习惯它
  • @Wyck stackoverflow.com/questions/31844058/… - 您不能直接在字符串插值中使用三元表达式,因为冒号 (:) 已用于格式字符串。
  • 我觉得这个if-else还不错。

标签: c#


【解决方案1】:

你可以这样做:

finalstr = "Hello " + (condition ? "A" : "B");

finalstr = $"Hello { (condition ? "A" : "B") }";

或使用string.Format

finalstr = string.Format("Hello {0}", condition ? "A" : "B");

或者您可以创建一个适合您需求的扩展:

public static class StringExtension
{
    // it's not needed since C# supports ternary, but I did it anyway 
    public static string If(this string str, Func<string, string> condition)
    {
        return string.IsNullOrWhiteSpace(str) ? str : $"{str} {condition(str)}";
    }
}

那么你可以这样做:

finalstr = "Hello".If(x => x == str ? "A" : "B");

【讨论】:

    【解决方案2】:

    关于条件的简单数字示例,对于超过 2 个结果:

    var c = 1; // Algorithm / console input / etc...
    
    var result = "hello " + c switch
    {
        1 => "variant a",
        2 => "variant b",
        _ => "default variant if there is no specific match"
    };
    

    所述条件不必是数字,这种模式基本上适用于其他所有条件。

    【讨论】:

    • 对于所提出的问题(即基于布尔条件),这仍然比 cmets 中的任何一个选项都复杂得多。
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2016-06-08
    • 2018-12-05
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多