C# 字符串前面的$是什么意思?

C# 字符串前面的$是什么意思?,c#,string,C#,String,我本来打算使用逐字字符串,但我错误地键入了$,而不是@ 但是编译器没有给我任何错误,编译成功了 我想知道它是什么,它做什么。我找过了,但什么也没找到 但是,它与逐字记录字符串不同,因为我无法编写: string str = $"text\"; 有人知道字符串在C#中代表什么吗 我使用的是Visual studio 2015 CTP。$是String.Format的缩写,用于字符串插值,这是C#6的一个新功能。正如在您的案例中所使用的,它什么也不做,就像string.Format()什么也不做一

我本来打算使用逐字字符串,但我错误地键入了
$
,而不是
@

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

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

但是,它与逐字记录字符串不同,因为我无法编写:

string str = $"text\";
有人知道字符串在C#中代表什么吗


我使用的是Visual studio 2015 CTP。

$
String.Format
的缩写,用于字符串插值,这是C#6的一个新功能。正如在您的案例中所使用的,它什么也不做,就像
string.Format()
什么也不做一样

当它用于构建引用其他值的字符串时,它就有了自己的特性。以前必须写的内容是:

var anInt = 1;
var aBool = true;
var aString = "3";
var formated = string.Format("{0},{1},{2}", anInt, aBool, aString);
现在变成:

var anInt = 1;
var aBool = true;
var aString = "3";
var formated = $"{anInt},{aBool},{aString}";
还有另一种不太为人所知的字符串插值形式,使用
$@
(两个符号的顺序很重要)。它允许将
@“
字符串的功能与
$”
混合,以支持字符串插值,而无需在整个字符串中使用
\
。因此,以下两行:

var someDir = "a";
Console.WriteLine($@"c:\{someDir}\b\c");
将输出:

c:\a\b\c

示例代码

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 text = "World";
var message = $"Hello, {text}";
执行上述两行后,变量
message
包含“Hello,World”

参考-

它创建了一个

用于构造字符串。插值字符串表达式 类似于包含表达式的模板字符串 字符串表达式通过替换包含的 表达式的ToString表示形式 结果

例:

可以在插值字符串中使用表达式

 var msg = $"hello, {name.ToLower()}";
 Console.WriteLine(msg); // hello, sam
它的好处是,您不需要像处理
String.Format
那样担心参数的顺序

  var s = String.Format("{0},{1},{2}...{88}",p0,p1,..,p88);
现在,如果你想删除一些参数,你必须去更新所有的计数,现在已经不是这样了


请注意,如果要在中指定文化信息,良好的旧
字符串.format
仍然是相关的。

请注意,您还可以将两者结合起来,这非常酷(尽管看起来有点奇怪):


它表示字符串插值

它将保护您,因为它将在字符串计算中添加编译时保护


使用
string.Format(“{0}{1}”,secondparamissing)将不再出现异常

它比string.Format更方便,您也可以在此处使用intellisense

这是我的测试方法:

[TestMethod]
public void StringMethodsTest_DollarSign()
{
    string name = "Forrest";
    string surname = "Gump";
    int year = 3; 
    string sDollarSign = $"My name is {name} {surname} and once I run more than {year} years."; 
    string expectedResult = "My name is Forrest Gump and once I run more than 3 years."; 
    Assert.AreEqual(expectedResult, sDollarSign);
}

很酷的特性。我只想指出,如果对某些人来说不明显的话,为什么这比string.format好

我读到有人说将string.format排序为“{0}{1}{2}”以匹配参数。你不必在string.format中对“{0}{1}{2}”排序,你也可以对“{2}{0}{1}”排序。但是,如果你有很多参数,比如20个,你真的想将字符串排序为“{0}{1}{2}…”…{19}”.如果这是一个混乱的局面,你将很难调整你的参数

使用$,您可以在不计算参数的情况下添加内联参数。这使代码更易于阅读和维护

$的缺点是,您不能轻易地在字符串中重复参数,您必须键入它。例如,如果您厌倦了键入System.Environment.NewLine,您可以执行string.format(“…{0}…{0}…{0}”,System.Environment.NewLine),但在$中,您必须重复它。您不能执行$“{0}”并将其传递给string.format,因为$“{0}”返回“0”

在旁注中,我在另一份重复的tpoic中读到了一条评论。我无法评论,所以,在这里。他说

string msg = n + " sheep, " + m + " chickens";
创建多个字符串对象。实际上并非如此。如果在一行中执行此操作,则只会创建一个字符串并将其放置在字符串缓存中

1) string + string + string + string;
2) string.format()
3) stringBuilder.ToString()
4) $""
它们都返回一个字符串,并且只在缓存中创建一个值

另一方面:

string+= string2;
string+= string2;
string+= string2;
string+= string2;
在缓存中创建4个不同的值,因为有4个“;”

因此,编写如下代码会更容易,但您将创建五个插值字符串,正如Carlos Muñoz所更正的:

string msg = $"Hello this is {myName}, " +
  $"My phone number {myPhone}, " +
  $"My email {myEmail}, " +
  $"My address {myAddress}, and " +
  $"My preference {myPreference}.";

这会在缓存中创建一个字符串,而您的代码非常容易阅读。我不确定性能,但我相信MS会优化它,如果还没有这样做的话。

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

例如:

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

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

以下示例强调了使用插值字符串优于
string.Format()
的各种优点,只要干净易读。它还显示了
{}
像任何其他函数参数一样进行计算,就像调用
string.Format()
一样

using System;

public class Example
{
   public static void Main()
   {
      var name = "Horace";
      var age = 34;
      // replaces {name} with the value of name, "Horace"
      var s1 = $"He asked, \"Is your name {name}?\", but didn't wait for a reply.";
      Console.WriteLine(s1);

      // as age is an integer, we can use ":D3" to denote that
      // it should have leading zeroes and be 3 characters long
      // see https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
      //
      // (age == 1 ? "" : "s") uses the ternary operator to 
      // decide the value used in the placeholder, the same 
      // as if it had been placed as an argument of string.Format
      //
      // finally, it shows that you can actually have quoted strings within strings
      // e.g. $"outer { "inner" } string"
      var s2 = $"{name} is {age:D3} year{(age == 1 ? "" : "s")} old.";
      Console.WriteLine(s2); 
   }
}
// The example displays the following output:
//       He asked, "Is your name Horace?", but didn't wait for a reply.
//       Horace is 034 years old.

$syntax很好,但有一个缺点

如果您需要字符串模板之类的东西,那么它将在类级别声明为字段…并且应该在一个位置

然后你必须在同一级别上声明变量…这不是很酷

这对我们好得多
string+= string2;
string+= string2;
string+= string2;
string+= string2;
string msg = $"Hello this is {myName}, " +
  $"My phone number {myPhone}, " +
  $"My email {myEmail}, " +
  $"My address {myAddress}, and " +
  $"My preference {myPreference}.";
Console.WriteLine($"I can tab like {"this !", 5}.");
using System;

public class Example
{
   public static void Main()
   {
      var name = "Horace";
      var age = 34;
      // replaces {name} with the value of name, "Horace"
      var s1 = $"He asked, \"Is your name {name}?\", but didn't wait for a reply.";
      Console.WriteLine(s1);

      // as age is an integer, we can use ":D3" to denote that
      // it should have leading zeroes and be 3 characters long
      // see https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
      //
      // (age == 1 ? "" : "s") uses the ternary operator to 
      // decide the value used in the placeholder, the same 
      // as if it had been placed as an argument of string.Format
      //
      // finally, it shows that you can actually have quoted strings within strings
      // e.g. $"outer { "inner" } string"
      var s2 = $"{name} is {age:D3} year{(age == 1 ? "" : "s")} old.";
      Console.WriteLine(s2); 
   }
}
// The example displays the following output:
//       He asked, "Is your name Horace?", but didn't wait for a reply.
//       Horace is 034 years old.
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;
 }
}