字符串前$的含义是什么?

M.k*_*ary 235 c# string

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

但编译器没有给我任何错误和编译成功.

我想知道它是什么以及它做了什么.我搜索它但我找不到任何东西.

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

string str = $"text\";
Run Code Online (Sandbox Code Playgroud)

有没有人知道$C#之前的字符串代表什么.

string str = $"text";
Run Code Online (Sandbox Code Playgroud)

我正在使用Visual Studio 2015 CTP.

Dav*_*rno 390

$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);
Run Code Online (Sandbox Code Playgroud)

现在变成:

var anInt = 1;
var aBool = true;
var aString = "3";
var formated = $"{anInt},{aBool},{aString}";
Run Code Online (Sandbox Code Playgroud)

还有一种替代 - 不太为人所知 - 使用字符串插值形式$@ (两个符号的顺序很重要).它允许@""混合字符串的功能$""以支持字符串插值,而不需要\\遍历整个字符串.所以以下两行:

var someDir = "a";
Console.WriteLine($@"c:\{someDir}\b\c");
Run Code Online (Sandbox Code Playgroud)

将输出:

c:\a\b\c
Run Code Online (Sandbox Code Playgroud)

  • 请注意,它并不是真正使用String.Format,而是基于编译器的功能,而不是运行时功能. (23认同)
  • @Flater这与$符号无关.这与$符号存在之前的行为相同. (3认同)
  • 小注意,我今天学到了,如果你使用 `$@`,那么你必须使用 `""` 来转义 `"` 字符。当你只使用 `$` 时,情况并非如此。 (2认同)
  • 对于您认为逐字 (@) 和插值 ($) 符号顺序很重要的观点,这在 C# 8 中已得到纠正,因此顺序将不再重要。请参阅:http://www.devsanon.com/uncategorized/c-8-is-fixing-interpolated-verbatim-strings/ (2认同)

Sle*_*idi 37

它创建一个插值字符串.

来自MSDN

用于构造字符串.插值字符串表达式看起来像包含表达式的模板字符串.插值字符串表达式通过将包含的表达式替换为表达式结果的ToString表示来创建字符串.

例如:

 var name = "Sam";
 var msg = $"hello, {name}";

 Console.WriteLine(msg); // hello, Sam
Run Code Online (Sandbox Code Playgroud)

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

 var msg = $"hello, {name.ToLower()}";
 Console.WriteLine(msg); // hello, sam
Run Code Online (Sandbox Code Playgroud)

关于它的好处是你不需要像对待那样担心参数的顺序String.Format.

  var s = String.Format("{0},{1},{2}...{88}",p0,p1,..,p88);
Run Code Online (Sandbox Code Playgroud)

现在,如果你想删除一些参数,你必须更新所有的计数,这不再是这种情况.

请注意,string.format如果要在格式中指定文化信息,则旧版仍然相关.


Sav*_*ake 16

它是Interpolated Strings.您可以在任何可以使用字符串文字的地方使用插值字符串.当运行程序时,将使用插值字符串文字执行代码,代码通过计算插值表达式来计算新的字符串文字.每次执行内插字符串的代码时都会发生此计算.

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}");
Run Code Online (Sandbox Code Playgroud)

此示例生成一个字符串值,其中已计算所有字符串插值.它是最终结果并具有类型字符串.所有出现的双花括号都会(“{{“ and “}}”)转换为单个花括号.

如果,

Full-Name - Albert Einstein
Full-Name - Albert Einstein
Full-Name - Albert Einstein
Run Code Online (Sandbox Code Playgroud)

然后message包含"Sample,One".

string text = "World";
var message = $"Hello, {text}";
Run Code Online (Sandbox Code Playgroud)

Console.WriteLine(message); // Prints Hello, World
Run Code Online (Sandbox Code Playgroud)

产量

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}");
Run Code Online (Sandbox Code Playgroud)

参考 - MSDN


BoB*_*Dev 10

很酷的功能.我只想指出强调为什么这比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";
Run Code Online (Sandbox Code Playgroud)

创建多个字符串对象.事实并非如此.如果您在一行中执行此操作,它只会创建一个字符串并放在字符串缓存中.

1) string + string + string + string;
2) string.format()
3) stringBuilder.ToString()
4) $""
Run Code Online (Sandbox Code Playgroud)

它们都返回一个字符串,只在缓存中创建一个值.

另一方面:

string+= string2;
string+= string2;
string+= string2;
string+= string2;
Run Code Online (Sandbox Code Playgroud)

在缓存中创建4个不同的值,因为有4个";".

因此,编写如下代码会更容易,但是当CarlosMuñoz纠正时你会创建五个插值字符串:

string msg = $"Hello this is {myName}, " +
  $"My phone number {myPhone}, " +
  $"My email {myEmail}, " +
  $"My address {myAddress}, and " +
  $"My preference {myPreference}.";
Run Code Online (Sandbox Code Playgroud)

这会在缓存中创建一个单独的字符串,同时您可以轻松读取代码.我不确定性能,但是,我确信MS会优化它,如果还没有这样做的话.


mar*_*sze 8

请注意,您也可以将两者结合起来,这很酷(虽然看起来有点奇怪):

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

  • 如果只是你可以决定你输入`$ @`或`@ $`的顺序.不幸的是它只能是`$ @` (4认同)
  • 我只是说`$`基本上是一个隐含的函数调用,而`@`是文字的一部分,就像十进制文字中的`m`一样.这就是为什么只有一个逻辑顺序. (3认同)
  • @Bauss这很有道理.`@`定义了如何表示字符串文字.`$`是`string.Format`的快捷方式.把它想象成`$(@"");` (2认同)
  • 我知道这主要是为了演示`$`,但是为了最大程度的兼容性而不是硬编码目录分隔符是'/'还是'\',还避免了不可避免的搞砸导致双斜线或丢失斜杠应该有一个,我建议在使用目录和文件时使用`Path.Combine()`而不是使用字符串连接. (2认同)

sil*_*ver 6

它表示字符串插值.

它会保护您,因为它在字符串评估中添加了编译时保护.

您将不再获得例外 string.Format("{0}{1}",secondParamIsMissing)


Gor*_*ulu 6

它比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);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

以下示例强调了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.
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 6

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

如果你需要像字符串模板这样的东西,那就在类级别上声明为字段......好吧在一个地方应该是这样.

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

为这种事情使用string.Format语法要好得多

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);
 }
}
Run Code Online (Sandbox Code Playgroud)

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

 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;
 }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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

示例:

Console.WriteLine($"I can tab like {"this !", 5}.");
Run Code Online (Sandbox Code Playgroud)

当然,你可以取代"这个!" 任何变量或任何有意义的东西,就像您也可以更改选项卡一样.