如何在内插字符串中使用变量?

How to use variable inside interpolated string?

我正在尝试在内插字符串中使用变量,但运气不佳。我该怎么做?

var name = "mike";
var desc = "hello world {name}";
var t = $"{ desc }";
Console.WriteLine(t); // PRINTS: hello world {name}

这就是我想要实现的目标:

Console.WriteLine(t); // PRINTS: hello world mike

这可能吗?

例如,假设我有一个方法:

public string FormatString(string s) {
      var Now = DateTime.Now;
      return $s;
}

用法:

Console.WriteLine(FormatString("The time is {Now}"));

您缺少 $

var name = "mike";
var desc = $"hello world {name}"; // this needs be interpolated as well
var t = $"{desc}";
Console.WriteLine(t); // PRINTS: hello world mike

其他资源

$ - string interpolation (C# Reference)

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.


更新

but suppose I want to have a variable storing the string with {name} in it. Is there no way to achieve interpolation if its in a variable?

不,您必须使用标准 String.Format 令牌

var tokenString = "Something {0}";

String.Format(tokenString,someVariable); 

String.Format Method

Converts the value of objects to strings based on the formats specified and inserts them into another string.

Use String.Format if you need to insert the value of an object, variable, or expression into another string. For example, you can insert the value of a Decimal value into a string to display it to the user as a single string:

Composite Formatting

The .NET composite formatting feature takes a list of objects and a composite format string as input. A composite format string consists of fixed text intermixed with indexed placeholders, called format items, that correspond to the objects in the list. The formatting operation yields a result string that consists of the original fixed text intermixed with the string representation of the objects in the list.