03day输入及转义符的使用

C#中转义字符分2中,一种是\,一种是@。
     作用1、在字符串的前面加@表示取消字符串中的转义
例如 string path=@"d:\root\subdir";
作用2、如果用户定义的对象名和系统关键字冲突,可以在变量前面加入@
例如 string @Class="this is a test";
转义字符    字符名称    
\'    单引号    
\"    双引号    
\\    反斜杠    
\0    空字符    
\a    警报符    
\b    退格    
\f    换页    
\n    换行    
\r    回车    
\t    水平制表    
\v    垂直制表    
 一 字符串中的用法
Verbatim字符串
                       string sample = @"Hello";
string sample = @"Hello\tworld"; //生成Hello\tworld
以下是一个实用的示例:
string sample=@"C:\My Documents\sample.txt";
//结果为:C:\My Documents\sample.txt,如同语句:string sample="C:\\My Documents\\sample.txt"
    若想在Verbatim字符串内使用引号,必须使用附加的引号组将其转义。例如,生成字符串"Hi"的代码如下:
String s=@" " "Hi"""; //注意:两边都有3个引号
上述代码将生成下列字符串:
"Hi"
 字符@表示,其后的字符串是个“逐字字符串”(verbatim string)。
@只能对字符串常量作用。
1.用于文件路径
以下是引用片段:
string s_FilePath ="C:\\Program Files\\Microsoft.NET\\test.txt";
相当于
以下是引用片段:
string s_FilePath =@"C:\Program Files\Microsoft.NET\test.txt";
2.用@表示的字符串能够跨越数行。用于在CS中写JS或SQL代码比较方便。
以下是引用片段:
string s_MultiRows = @"Line1 
Line2 
Line3"; 
string s_JavaScript = @" 
"; 
二 标识符中的用法
在 C# 规范中, @ 可以作为标识符(类名、变量名、方法名等)的第一个字符,以允许C# 中保留关键字作为自己定义的标识符。
如
以下是引用片段:
class @class 
{ 
public static void @static(bool @bool) { 
if (@bool) 
System.Console.WriteLine("true"); 
else 
System.Console.WriteLine("false"); 
} 
} 
class Class1 
{ 
static void M() { 
clu0061ss.stu0061tic(true); 
} 
} 
注意,@ 虽然出现在标识符中,但不作为标识符本身的一部分。
因此,以上示例,定义了一个名为 class 的类,并包含一个名为 static 的方法,以及一个参数名为了 bool 的形参。
这样,对于跨语言的移植带来了便利。因为,某个单词在 C# 中作为保留关键字,但是在其他语言中也许不是。

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _03day输入
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             //获取用户输入Console.ReadLine()
14             
15             string input;
16             string zystr ="引号的使用\"\"后";
17             string path = @"d:\root\subdir"; //@表示取消字符串中的转义
18             Console.WriteLine("请输入你的内容");
19             input=Console.ReadLine();
20             Console.WriteLine("输入内容转义符的使用" + path + "");
21             Console.WriteLine("你刚才输出的内容是{0}",input);
22             Console.WriteLine(zystr);
23             Console.ReadKey();
24            
25         }
26     }
27 }

 

猜你喜欢

转载自www.cnblogs.com/cuojue/p/10507633.html