C# 中字符串插值内的字符串插值导致编译器错误

Tho*_*ann 7 c# csc string-interpolation

以下 C# 表达式会导致我的程序出现编译器错误:

$"Getting image from {location.IsLatitudeLongitude ? $"{location.Latitude} - {location.Longitude}" : location.Location}."
Run Code Online (Sandbox Code Playgroud)

难道不能像这样使用字符串插值吗?或者根本不可能做到这一点?

Kev*_*tch 6

根据文档,在字符串插值中使用三元运算符时,需要使用以下格式。

插值字符串的结构如下:

$ "{ <interpolation-expression> <optional-comma-field-width> <optional-colon-format> }"
Run Code Online (Sandbox Code Playgroud)

因此,您需要在 { 之后和结束 } 之前添加一组括号,如下所示:

$"Getting image from {(location.IsLatitudeLongitude ? $"{location.Latitude} - {location.Longitude}" : location.Location)}."
Run Code Online (Sandbox Code Playgroud)