欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中@的用法总结

程序员文章站 2023-12-22 09:48:58
本文实例汇总了c#中@的用法,对c#程序设计来说有不错的借鉴价值。具体如下: 一 字符串中的用法 1.学过c#的人都知道c# 中字符串常量可以以@ 开头声名,这样的优点...

本文实例汇总了c#中@的用法,对c#程序设计来说有不错的借鉴价值。具体如下:

一 字符串中的用法

1.学过c#的人都知道c# 中字符串常量可以以@ 开头声名,这样的优点是转义序列“不”被处理,按“原样”输出,即我们不需要对转义字符加上 \ (反斜扛),就可以轻松coding。如,

string filepath = @"c:\docs\source\a.txt" // rather than "c:\\docs\\source\\a.txt" 

2.如要在一个用 @ 引起来的字符串中包括一个双引号,就需要使用两对双引号了。这时候你不能使用 \ 来转义爽引号了,因为在这里 \ 的转义用途已经被 @  “屏蔽”掉了。如,

@"""ahoy!"" cried the captain."  // 输出为: "ahoy!" cried the captain. 

这有点像sql中的单引号常量处理方式:

declare @msg varchar(100) 
set @msg = ''ahoy!'' cried the captain.' -- 输出为: 'ahoy!' cried the captain. 

3.@会识别换行符

其实这个特性,我不知道怎么描述,只是偶然发现的,先来看看下面的代码:

string script = @" 
<script type=""type/javascript""> 
function dosomething() 
{ 
} 
</script>"; 

这段代码在cs文件中写js,结构就很清晰了,正常情况我们是这样coding的:

string script2 = "<script type=\"type/javascript\">function dosomething(){}</script>"; 

或者:

string script3 = 
"<script type=\"type/javascript\">" + 
"function dosomething(){ " + 
"}</script>"; 

通常我们会选择后者,因为js代码一般比较长,或者方法体很大,或者需要连接其他变量,这样结构比较清晰。

注意:如果“拼接”的次数很多,应该考虑使用stringbuilder了,有助于提高性能

还有一种场景,也很常见,在程序中拼接 sql 语句,如

private const string sql_ins_user = @" 
insert into t_user([username], [password], email)  
 values(@username, @password, @email)"; 

这样就像写存储过程一般,保持相当高的代码清晰度。然而,我们需要关注一个问题:字符串长度看下面的测试代码:

private const string sql_ins_user1 = @" 
  insert into t_user([username], [password], email)  
 values(@username, @password, @email)"; 

private const string sql_ins_user2 = @"insert into t_user([username], [password], email)  
 values(@username, @password, @email)"; 

private const string sql_ins_user3 = @"insert into t_user([username], [password], email) values(@username, @password, @email)";  

static void main(string[] args) 
{ 
  console.writeline(sql_ins_user1.length);  // 126  
  console.writeline(sql_ins_user2.length);  // 112 
  console.writeline(sql_ins_user3.length);  // 86 
} 

这里可以看到三个字符串长度分别相差了,14=126-112和26=112-86,注意观察了,在代码编辑器中,sql_ins_user1 中第一个换行符号之后,我缩进13个空格(insert之前),而
sql_ins_user2 中第一个换行符号之后,我缩进25个空格(values之前),
那么,加上一个换行符,刚刚好 14和26

如此编写代码,虽然提高了代码的清晰度和简便性,却无行中带来了另一个问题:字符长度!
很多场景下我们希望字符串越短越好,如,通过ado.net 发送 sql 语句给数据库执行。
所以还是慎用之!

二 标识符中的用法

在 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() { 
   cl\u0061ss.st\u0061tic(true); 
  } 
} 

注意,@虽然出现在标识符中,但不作为标识符本身的一部分。
因此,以上示例,定义了一个名为 class 的类,并包含一个名为 static 的方法,以及一个参数名为了 bool 的形参。

这样,对于跨语言的移植带来了便利。因为,某个单词在 c#  中作为保留关键字,但是在其他语言中也许不是。

上一篇:

下一篇: