• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

c#中@标志的作用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/tokens/verbatim

1、在变量名前加@,可以告诉编译器,@后的就是变量名。主要用于变量名和C#关键字重复时使用。

string[] @for = { "John", "James", "Joan", "Jamie" };
for (int ctr = 0; ctr < @for.Length; ctr++)
{
   Console.WriteLine($"Here is your gift, {@for[ctr]}!");
}
// The example displays the following output:
//     Here is your gift, John!
//     Here is your gift, James!
//     Here is your gift, Joan!
//     Here is your gift, Jamie!

2、在字符串前加@,字符串中的转义字符串将不再转义。例外:""仍将转义为",{{和}}仍将转义为{和}。在同时使用字符串内插和逐字字符串时,$要在@的前面

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

Console.WriteLine(filename1);
Console.WriteLine(filename2);
// The example displays the following output:
//     c:\documents\files\u0066.txt
//     c:\documents\files\u0066.txt

3、类似于第一条,用于在命名冲突时区分两个特性名。特性Attribute自定义的类型名称在起名时应以Attribute结尾,例如InfoAttribute,之后我们可以用InfoAttribute或Info来引用它。但是如果我们定义了两个自定义特性,分别命名Info和InfoAttribute,则在使用Info这个名字时,编译器就不知道是哪个了。这时,如果想用Info,就用@Info,想用InfoAttribute,就把名字写全。

using System;

[AttributeUsage(AttributeTargets.Class)]
public class Info : Attribute
{
   private string information;
   
   public Info(string info)
   {
      information = info;
   }
}

[AttributeUsage(AttributeTargets.Method)]
public class InfoAttribute : Attribute
{
   private string information;
   
   public InfoAttribute(string info)
   {
      information = info;
   }
}

[Info("A simple executable.")] // Generates compiler error CS1614. Ambiguous Info and InfoAttribute. 
// Prepend '@' to select 'Info'. Specify the full name 'InfoAttribute' to select it.
public class Example
{
   [InfoAttribute("The entry point.")]
   public static void Main()
   {
   }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#获取本机IP地址以及转换字符串发布时间:2022-07-10
下一篇:
C#调用页面中的窗体中的方法,获取窗体的元素。发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap