如何在字符串中使用“\”而不使其成为转义序列 - C#?

问题描述 投票:0回答:7

我确信这是我不知道的非常基本的东西,但是我如何让它不将“\”识别为字符串内的转义序列

我正在尝试输入路径,它认为这是一个转义序列

c# escaping
7个回答
69
投票

您可以使用逐字字符串文字

//Initialize with a regular string literal.
string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";

// Initialize with a verbatim string literal.
string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";
                 ↑

8
投票
string s = @"C:\Temp";

5
投票

使用“\”

有趣的事情:我不得不使用 \ 来逃避 \。


3
投票

很简单... 只需将“@”符号放在字符串之前,它就不会关心你的转义序列...就像这样

字符串名称=@"lndebi 因德比”;

输出将为 lndebi 因德比。


1
投票

很简单,只需做两个斜杠:

\


1
投票

您可以使用“\”代替“\”以及开头的“@”符号。


0
投票

从 2022 年 11 月发布的 C# 11 和 .NET 7 开始,您可以使用 Raw String Literals 来避免转义字符。

原始字符串文字

原始字符串文字以至少三个双引号 (") 字符开头和结尾:

string example = """This is a "raw string literal". It can contain characters like \, ' and ".""";

Console.WriteLine(example);

// Output is:
// This is a "raw string literal". It can contain characters like \, ' and ".

原始字符串文字可以包含任意文本,包括空格、换行符、嵌入引号和其他特殊字符无需转义序列。原始字符串文字至少以三个双引号 (""") 字符开头。它以相同数量的双引号字符结尾。通常,原始字符串文字在单行上使用三个双引号来启动字符串,并在单独的行上使用三个双引号来结束字符串。开始引号后面和结束引号之前的换行符不包含在最终内容中,并且结束双引号左侧的任何空格都将从字符串文字中删除:

string longMessage = """
    This is a long message.
    It has several lines.
        Some are indented
                more than others.
    Some should start at the first column.
    Some have "quoted text" in them.
    """;
    
Console.WriteLine(longMessage);

// Output is:
/*
This is a long message.
It has several lines.
    Some are indented
        more than others.
Some should start at the first column.
Some have "quoted text" in them.
*/

内插的原始字符串文字

原始字符串文字可以与字符串插值结合使用,以在输出文本中包含大括号。

int X = 2;
int Y = 3;

var pointMessage = $"""The point "{X}, {Y}" is {Math.Sqrt(X * X + Y * Y):F3} from the origin""";

Console.WriteLine(pointMessage);
// Output is:
// The point "2, 3" is 3.606 from the origin

多个 $ 字符表示有多少个连续的大括号开始和结束插值:

string latitude = "38.8977° N";
string longitude = "77.0365° W";

var location = $$"""
    You are at {{{latitude}}, {{longitude}}}
    """;
    
Console.WriteLine(location);

// Output is:
// You are at {38.8977° N, 77.0365° W}

前面的示例指定两个大括号开始和结束插值。第三个重复的左大括号和右大括号包含在输出字符串中。


参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.