在字符串中使用变量

thw*_*hwd 76 c# string string-formatting

在PHP中,我可以执行以下操作:

$name = 'John';
$var = "Hello {$name}";    // => Hello John
Run Code Online (Sandbox Code Playgroud)

C#中是否有类似的语言结构?

我知道有,String.Format();但我想知道是否可以在不调用字符串上的函数/方法的情况下完成.

Fen*_*ton 191

在C#6中,您可以使用字符串插值:

string name = "John";
string result = $"Hello {name}";
Run Code Online (Sandbox Code Playgroud)

在Visual Studio中为此突出显示的语法使其具有高可读性,并检查所有标记.


Sco*_*pey 81

此功能不是内置于C#5或更低版本.
更新:C#6现在支持字符串插值,请参阅更新的答案.

建议的方法是String.Format:

string name = "Scott";
string output = String.Format("Hello {0}", name);
Run Code Online (Sandbox Code Playgroud)

但是,我编写了一个名为SmartFormat的小型开源库String.Format,它扩展了它可以使用命名占位符(通过反射).所以,你可以这样做:

string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".
Run Code Online (Sandbox Code Playgroud)

希望你喜欢!

  • 使用反射实现与标准string.Format有什么样的性能损失? (2认同)

小智 10

使用以下方法

1:方法一

var count = 123;
var message = $"Rows count is: {count}";
Run Code Online (Sandbox Code Playgroud)

2:方法二

var count = 123;
var message = "Rows count is:" + count;
Run Code Online (Sandbox Code Playgroud)

3:方法三

var count = 123;
var message = string.Format("Rows count is:{0}", count);
Run Code Online (Sandbox Code Playgroud)

4:方法四

var count = 123;
var message = @"Rows
                count
                is:{0}" + count;
Run Code Online (Sandbox Code Playgroud)

5:方法五

var count = 123;
var message = $@"Rows 
                 count 
                 is: {count}";
Run Code Online (Sandbox Code Playgroud)

  • 最好添加一条注释来说明为什么您会选择使用这些方法。 (2认同)

And*_*bel 6

直到C#5(-VS2013)你必须为它调用一个函数/方法.要么是"正常"函数,String.Format要么是+运算符的重载.

string str = "Hello " + name; // This calls an overload of operator +.
Run Code Online (Sandbox Code Playgroud)

在C#6(VS2015)中,引入了字符串插值(如其他答案所述).