C#中的关键字@

打印 上一主题 下一主题

主题 903|帖子 903|积分 2709

C#中的@关键字

@作为C#中的特别字符,在Microsoft文档中定义为Verbatim文本
Verbatim的解释为完全一致大概逐字逐句,比方verbatim 地引用了一段笔墨:
“The researcher stated verbatim: ‘The results indicate a significant correlation between variables.’”
有三种主要的应用场景
1.定义Verbatim字符串文本
  1. string filename1 = @"c:\documents\files\u0066.txt";
  2. string filename2 = "c:\\documents\\files\\u0066.txt";
  3. Console.WriteLine(filename1);
  4. Console.WriteLine(filename2);
  5. //输出结果:
  6. //     c:\documents\files\u0066.txt
  7. //     c:\documents\files\u0066.txt
复制代码
注意:

  • 利用插值字符串时,{和}会优先被$解析
  1. string s = "World";
  2. Console.WriteLine($@"Hello, {s}!");
  3. //输出结果
  4. //Hello, World!
复制代码
不利用$:
  1. string s = "World";
  2. Console.WriteLine(@"Hello, {s}!");
  3. //输出结果
  4. //Hello, {s}!
复制代码

  • 在Verbatim字符串利用",需要利用两个引号,单个利用会解释为字符串结束
  1. string s1 = "He said, "This is the last \u0063hance\x0021"";
  2. string s2 = @"He said, ""This is the last \u0063hance\x0021""";
  3. Console.WriteLine(s1);
  4. Console.WriteLine(s2);
  5. // 输出结果:
  6. //     He said, "This is the last chance!"
  7. //     He said, "This is the last \u0063hance\x0021"
复制代码
2.利用C#中的同名关键字作为标识符

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

属性是从 Attribute 派生的类。其类型名称通常包含后缀 Attribute,尽管编译器不逼迫实行此约定。然后,可以在代码中通过其完整类型名称(比方 [InfoAttribute]或其缩写名称(比方 [Info])引用该属性。但是,如果两个收缩的属性类型名称相同,而且一个类型名称包含 Attribute 后缀,而另一个类型名称不包含,则会发生命名辩论。
比方,下面的代码无法编译,由于编译器无法确定 Info 或 InfoAttribute 属性是否应用于 Example 类。
  1. using System;
  2. [AttributeUsage(AttributeTargets.Class)]
  3. public class Info : Attribute
  4. {
  5.    private string information;
  6.    public Info(string info)
  7.    {
  8.       information = info;
  9.    }
  10. }
  11. [AttributeUsage(AttributeTargets.Method)]
  12. public class InfoAttribute : Attribute
  13. {
  14.    private string information;
  15.    public InfoAttribute(string info)
  16.    {
  17.       information = info;
  18.    }
  19. }
  20. [Info("A simple executable.")] // 编译错误CS1614. Ambiguous Info and InfoAttribute.
  21. //正确写法:使用Info属性 [@Info("A simple executable.")] .使用InfoAttribute属性 [@Info("A simple executable.")]
  22. public class Example
  23. {
  24.    [InfoAttribute("The entry point.")]
  25.    public static void Main()
  26.    {
  27.    }
  28. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

麻花痒

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表