private static readonly string formatString = "This is {0}overflow";
...
var strVar = "stack";
var myStr = string.Format(formatString, "stack");
另一种方法是使用 C # 连接操作符:
var strVar = "stack";
var myStr = "This is " + strVar + "overflow";
如果你要进行大量的串联操作,那么使用 StringBuilder类会更有效:
var strVar = "stack";
var stringBuilder = new StringBuilder("This is ");
for (;;)
{
stringBuilder.Append(strVar); // spot the deliberate mistake ;-)
}
stringBuilder.Append("overflow");
var myStr = stringBuilder.ToString();
var planetName = "Bob";
var myName = "Ford";
var formattedStr = $"Hello planet {planetName}, my name is {myName}!";
// formattedStr should be "Hello planet Bob, my name is Ford!"
这是代表:
var formattedStr = String.Format("Hello planet {0}, my name is {1}!", planetName, myName);
var name = "Vikas";
Console.WriteLine($"My name is {name}");
添加特殊字符 :
string name = "John";
Console.WriteLine($"Hello, \"are you {name}?\", but not the terminator movie one :-\{\{");
//output-Hello, "are you John?", but not the terminator movie one :-{
不仅仅是用 value 替换标记,在 C # 中使用字符串插值还可以做更多的事情
评估表达式
Console.WriteLine($"The greater one is: { Math.Max(10, 20) }");
//output - The greater one is: 20
方法调用
static void Main(string[] args)
{
Console.WriteLine($"The 5*5 is {MultipleByItSelf(5)}");
}
static int MultipleByItSelf(int num)
{
return num * num;
}