简体   繁体   English

字符串插值 C#

[英]String Interpolation C#

If we can one store the temp_data of a string in a variable and use interpolation on it?如果我们可以将字符串的 temp_data 存储在变量中并对其使用插值?

var name = "John";

var temp_data = "Hi {name}";

var result_data = $temp_data;

If their any possible solution are available other than string.Format() and string.Replace()如果除了string.Format()string.Replace()之外,还有任何可能的解决方案可用

If you wish to store the message as an external resource you will need to use string.Format rather than string interpolation, interpolated strings have to exist in their entirety at compile time as string literals.如果您希望将消息存储为外部资源,您将需要使用 string.Format 而不是字符串插值,内插字符串必须在编译时作为字符串文字完整存在。

You will also need to ensure that the number of variables contained in the message match those in the code calling string.format otherwise it will not transpose correctly.您还需要确保消息中包含的变量数量与调用 string.format 的代码中的变量数量相匹配,否则将无法正确转置。

As an example, this is using a resource file;例如,这是使用资源文件;

var message = string.Format(Strings.ErrorMessage, value1, value2);

Strings.ErrorMessage would contain; Strings.ErrorMessage 将包含;

"This is the error {0} and message {1}" “这是错误 {0} 和消息 {1}”

您可以使用$ - string interpolation (C# Reference) https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

you can use like this你可以这样使用

double speedOfLight = 299792.458;
FormattableString message = $"The speed of light is {speedOfLight:N3} km/s.";

System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = message.ToString();

var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCulture);

string messageInInvariantCulture = FormattableString.Invariant(message);

Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");

Using C#6, you can do exactly what you wrote, without the typo :使用 C#6,你可以完全按照你写的做,没有错字:

var name = "John";

var temp_data = $"Hi {name}";

var result_data = temp_data;

Console.log(result_data);

will return "Hi John" ;)将返回“嗨约翰”;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM