码迷,mamicode.com
首页 > 其他好文 > 详细

_02特性 给方法加上注释 或者停用

时间:2018-09-26 17:11:53      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:bsp   pat   gets   runtime   linq   路径   mat   number   value   

1.主函数的代码,先是验证已经有的特性:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Diagnostics;
 4 using System.Linq;
 5 using System.Runtime.CompilerServices;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace _02特性
10 {
11     [myTeXing("啊韩国",Id =45)]
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             //创建自己的特性
17          Type t=   typeof(Program);//创建
18             object[] obj = t.GetCustomAttributes(false);
19             foreach (var item in obj)
20             {
21                 Console.WriteLine(item);////输出类名
22                 Console.WriteLine(((myTeXingAttribute)item).Name);//输出名字
23                 Console.WriteLine(((myTeXingAttribute)item).Id);//输出id
24             }
25             //text();
26             ////text1();//特性Obsolete为true该方法就不能使用了
27             //text2();//已经被注释 输不出了
28             //text3("笑话");//有[]个的可以不用加参数的
29 
30         }
31 
32         //调用已经有的特性
33         [Obsolete("这个方法还可以用一段时间")]//当光标在方法上时候会有提示 该方法还可以用
34         public static void text()
35         {
36             Console.WriteLine("text");
37         }
38 
39         [Obsolete("该程序禁止使用", true)]//该方是可以用来代码升级的时候,又不舍得丢弃老代码的时候实用
40         public static void text1()
41         {
42             Console.WriteLine("text1");
43         }
44 
45        [Conditional("text2")]//该方法被注释掉了(字符串作为标记进行注释) 主函数已经调用不出来了
46         public static void text2()
47         {
48             Console.WriteLine("text2");
49         }
50 
51        //输出加上去的特性 把文件名字 路径 都显示了
52         public static void text3(string name,[CallerFilePath]string filepath="",[CallerLineNumber]int num=11,[CallerMemberName]string filename="")
53         {
54             Console.WriteLine("text3");
55             Console.WriteLine(name + filepath + num + filename);
56 
57         }
58     }
59 }

2.自己创建个特性,在主函数里面调用:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _02特性
 8 {
 9     //1.特性类尾缀加上Attribute 
10     //2.必须引用特性[AttributeUsage]并继承于System.Attribute 
11     //3.特性内一般只有属性没有方法 4.构造函数内可以添加参数 
12 
13     [AttributeUsage(AttributeTargets.Class)]
14     class myTeXingAttribute:System.Attribute
15     {
16 
17         string name;
18         int id;
19 
20         public string Name { get => name; set => name = value; }
21         public int Id { get => id; set => id = value; }
22         public myTeXingAttribute(string name)
23         {
24             this.Name = name;
25         }
26     }
27 }

 

_02特性 给方法加上注释 或者停用

标签:bsp   pat   gets   runtime   linq   路径   mat   number   value   

原文地址:https://www.cnblogs.com/satanj/p/9707683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!