Using variables inside strings

后端 未结 4 1330
执笔经年
执笔经年 2020-11-27 04:45

In PHP I can do the following:

$name = \'John\';
$var = \"Hello {$name}\";    // => Hello John

Is there a similar language construct in

相关标签:
4条回答
  • 2020-11-27 05:19

    This functionality is not built-in to C# 5 or below.
    Update: C# 6 now supports string interpolation, see newer answers.

    The recommended way to do this would be with String.Format:

    string name = "Scott";
    string output = String.Format("Hello {0}", name);
    

    However, I wrote a small open-source library called SmartFormat that extends String.Format so that it can use named placeholders (via reflection). So, you could do:

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

    Hope you like it!

    0 讨论(0)
  • 2020-11-27 05:20

    Up to C#5 (-VS2013) you have to call a function/method for it. Either a "normal" function such as String.Format or an overload of the + operator.

    string str = "Hello " + name; // This calls an overload of operator +.
    

    In C#6 (VS2015) string interpolation has been introduced (as described by other answers).

    0 讨论(0)
  • 2020-11-27 05:22

    Use the following methods

    1: Method one

    var count = 123;
    var message = $"Rows count is: {count}";
    

    2: Method two

    var count = 123;
    var message = "Rows count is:" + count;
    

    3: Method three

    var count = 123;
    var message = string.Format("Rows count is:{0}", count);
    

    4: Method four

    var count = 123;
    var message = @"Rows
                    count
                    is:{0}" + count;
    

    5: Method five

    var count = 123;
    var message = $@"Rows 
                     count 
                     is: {count}";
    
    0 讨论(0)
  • 2020-11-27 05:37

    In C# 6 you can use string interpolation:

    string name = "John";
    string result = $"Hello {name}";
    

    The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

    0 讨论(0)
提交回复
热议问题