麻花痒 发表于 7 天前

C#中的关键字@

C#中的@关键字

@作为C#中的特别字符,在Microsoft文档中定义为Verbatim文本
Verbatim的解释为完全一致大概逐字逐句,比方verbatim 地引用了一段笔墨:
“The researcher stated verbatim: ‘The results indicate a significant correlation between variables.’”
有三种主要的应用场景
1.定义Verbatim字符串文本

string filename1 = @"c:\documents\files\u0066.txt";
string filename2 = "c:\\documents\\files\\u0066.txt";

Console.WriteLine(filename1);
Console.WriteLine(filename2);
//输出结果:
//   c:\documents\files\u0066.txt
//   c:\documents\files\u0066.txt注意:

[*]利用插值字符串时,{和}会优先被$解析
string s = "World";
Console.WriteLine($@"Hello, {s}!");
//输出结果
//Hello, World!不利用$:
string s = "World";
Console.WriteLine(@"Hello, {s}!");
//输出结果
//Hello, {s}!

[*]在Verbatim字符串利用",需要利用两个引号,单个利用会解释为字符串结束
string s1 = "He said, \"This is the last \u0063hance\x0021\"";
string s2 = @"He said, ""This is the last \u0063hance\x0021""";

Console.WriteLine(s1);
Console.WriteLine(s2);
// 输出结果:
//   He said, "This is the last chance!"
//   He said, "This is the last \u0063hance\x0021"2.利用C#中的同名关键字作为标识符

比方,利用for作为数组名称
string[] @for = { "John", "James", "Joan", "Jamie" };
for (int ctr = 0; ctr < @for.Length; ctr++)
{
   Console.WriteLine($"Here is your gift, {@for}!");
}
//输出结果:
//   Here is your gift, John!
//   Here is your gift, James!
//   Here is your gift, Joan!
//   Here is your gift, Jamie!3.解决属性辩论

属性是从 Attribute 派生的类。其类型名称通常包含后缀 Attribute,尽管编译器不逼迫实行此约定。然后,可以在代码中通过其完整类型名称(比方 或其缩写名称(比方 )引用该属性。但是,如果两个收缩的属性类型名称相同,而且一个类型名称包含 Attribute 后缀,而另一个类型名称不包含,则会发生命名辩论。
比方,下面的代码无法编译,由于编译器无法确定 Info 或 InfoAttribute 属性是否应用于 Example 类。
using System;


public class Info : Attribute
{
   private string information;

   public Info(string info)
   {
      information = info;
   }
}


public class InfoAttribute : Attribute
{
   private string information;

   public InfoAttribute(string info)
   {
      information = info;
   }
}

// 编译错误CS1614. Ambiguous Info and InfoAttribute.
//正确写法:使用Info属性 [@Info("A simple executable.")] .使用InfoAttribute属性 [@Info("A simple executable.")]
public class Example
{
   
   public static void Main()
   {
   }
}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: C#中的关键字@