如何在字符串插值中使用条件运算符?

How to use conditional operator with string interpolation?

I am currently using this technique:

...
    string s = user.Gender ? "Mr." : "Mrs.";
    string body = $@"Dear {s} {user.First_name}..."
...

I want to do something like:

...
    string body = $"Dear {return user.Gender ? "Mr." : "Mrs."} {user.First_name}..."
...

你可以这样使用

bool flag  = true;
string body = $"Dear {(flag ? "Mr." : "Mrs.")}";

您需要在表达式两边加上括号,如下所示:

string body = $"Dear {(user.Gender ? "Mr." : "Mrs.")} {user.First_name}...";

原因是冒号表示某物的格式字符串。

您可以使用条件表达式周围的一对括号轻松地做到这一点,但更好的解决方案是通过在 class 上定义 属性 来使问候语可重用:

public class User {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool Gender { get; set; }
    public string Title { get => Gender ? "Mr." : "Mrs."; }
    public string Greeting { get => $"{Title} {FirstName} {LastName}"; }
}

void run()
{
    var user = new User { Gender = true, FirstName = "John", LastName = "Smith" };
    string simpleSolution = $"Dear {(user.Gender ? "Mr." : "Mrs.")} {user.FirstName} {user.LastName}, hello and welcome.";
    string betterSolution = $"Dear {user.Greeting}, hello and welcome.";
}