我打算使用逐字字符串,但我错误地输入$而不是@。

但是编译器没有给我任何错误,并成功编译。

我想知道它是什么,有什么作用。我找过了,但什么也没找到。

然而,它不像一个逐字字符串,因为我不能写:

string str = $"text\";

在c#中字符串前面的$字符是什么意思?

string str = $"text";

我使用Visual studio 2015 CTP。


当前回答

注意,你也可以将两者结合起来,这很酷(尽管看起来有点奇怪):

// simple interpolated verbatim string
WriteLine($@"Path ""C:\Windows\{file}"" not found.");

其他回答

注意,你也可以将两者结合起来,这很酷(尽管看起来有点奇怪):

// simple interpolated verbatim string
WriteLine($@"Path ""C:\Windows\{file}"" not found.");

它表示字符串插值。

它会保护你,因为它在字符串求值上增加了编译时间保护。

你将不再得到string.Format("{0}{1}",secondParamIsMissing)异常

示例代码

public class Person {
    public String firstName { get; set; }
    public String lastName { get; set; }
}

// Instantiate Person
var person = new Person { firstName = "Albert", lastName = "Einstein" };

// We can print fullname of the above person as follows
Console.WriteLine("Full-Name - " + person.firstName + " " + person.lastName);
Console.WriteLine("Full-Name - {0} {1}", person.firstName, person.lastName);
Console.WriteLine($"Full-Name - {person.firstName} {person.lastName}");

输出

Full-Name - Albert Einstein
Full-Name - Albert Einstein
Full-Name - Albert Einstein

它是插值字符串。可以在任何可以使用字符串字面量的地方使用插值字符串。当运行您的程序将使用插值字符串文字执行代码时,代码将通过计算插值表达式计算一个新的字符串文字。每次执行带有插值字符串的代码时都会进行此计算。

以下示例生成一个字符串值,其中所有字符串插值值都已计算完毕。它是最终结果,类型为string。所有出现的双大括号(“{{”和“}}”)都被转换为单个大括号。

string text = "World";
var message = $"Hello, {text}";

执行以上2行后,变量message包含“Hello, World”。

Console.WriteLine(message); // Prints Hello, World

参考资料- MSDN

$语法很好,但有一个缺点。

如果你需要一个字符串模板,在类级别上声明为field…它本该在一个地方。

然后你必须在同一层次上声明变量…这一点都不酷。

使用字符串要好得多。这类事情的格式语法

class Example1_StringFormat {
 string template = $"{0} - {1}";

 public string FormatExample1() {
   string some1 = "someone";
   return string.Format(template, some1, "inplacesomethingelse");
 }

 public string FormatExample2() {
   string some2 = "someoneelse";
   string thing2 = "somethingelse";
   return string.Format(template, some2, thing2);
 }
}

全局变量的使用并不是很好,除此之外,它也不适用于全局变量

 static class Example2_Format {
 //must have declaration in same scope
 static string some = "";
 static string thing = "";
 static string template = $"{some} - {thing}";

//This returns " - " and not "someone - something" as you would maybe 
//expect
 public static string FormatExample1() {
   some = "someone";
   thing = "something";
   return template;
 }

//This returns " - " and not "someoneelse- somethingelse" as you would 
//maybe expect
 public static string FormatExample2() {
   some = "someoneelse";
   thing = "somethingelse";
   return template;
 }
}

我不知道它是如何工作的,但你也可以用它来标记你的值!

例子:

Console.WriteLine($"I can tab like {"this !", 5}.");

当然,您可以将“this !”替换为任何变量或任何有意义的内容,就像您也可以更改选项卡一样。