与格式变量字符串插值 [英] String Interpolation with format variable

查看:143
本文介绍了与格式变量字符串插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样做:

var log = string.Format("URL: {0}", url);



也不像这个

or even like this

var format = "URL: {0}";
...
var log = string.Format(format, url);



我有一个格式定义别的地方,使用格式变量,而不是内联字符串

I have a format defined somewhere else and use the format variable, not inline string.

在C#6,这似乎是不可能的:

In C# 6, this is seems impossible:

var format = $"URL: {url}"; // Error url does not exist
...
var url = "http://google.com";
...
var log = $format; // The way to evaluate string interpolation here



反正是有使用字符串插值可变早些时候宣布?

Is there anyway to use string interpolation with variable declared earlier?

C#6似乎在编译时内嵌插值字符串。不过考虑使用此功能定位,在配置中定义的格式或者只是有一个类中的格式为:常量

C# 6 seems interpolate the string inline during compile time. However consider using this feature for localization, define a format in config or simply having a format const in a class.

推荐答案

没有,因为编译器会创建一个不能使用的字符串插补不是字符串文本以外的东西,甚至当你使用字符串插值常规格式字符串。

No, you can't use string interpolation with something other than a string literal as the compiler creates a "regular" format string even when you use string interpolation.

由于这样的:

string name = "bar";
string result = $"{name}";



被编译成这样的:

is compiled into this:

string name = "bar";
string result = string.Format("{0}", name);

在运行时字符串必须是常规格式的字符串,而不是字符串插值等价的。

the string in runtime must be a "regular" format string and not the string interpolation equivalent.

您可以使用普通的老式的String.Format 代替。

You can use the plain old String.Format instead.

这篇关于与格式变量字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆