• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
白染
博客园    首页    新随笔    联系   管理    订阅  订阅

C#:特性

#define IsText//添加一个宏,接触注释
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace _002特性
{
    [MyText("张三",Id =20)]
    class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(Program);
            object[] obj = type.GetCustomAttributes(false);
            foreach (var item in obj)
            {
                Console.WriteLine(item);
                Console.WriteLine(((MyTextAttribute)item).Name);
                Console.WriteLine(((MyTextAttribute)item).Id);
            }
           // Text1();
            //Text2();特性Obsolete为true程序就不能使用了
            //Text3();
            //Text4("张三");
        }
        [Obsolete("这个程序还可以用一段时间")]
        public static void Text1()
        {
            Console.WriteLine("Text1");
        }
        [Obsolete("该程序作废,禁止使用",true)]
        public static void Text2()
        {
            Console.WriteLine("Text2");
        }
       [Conditional("IsText")]//该方法被注释掉了(字符串作为标记进行注释)
        public static void Text3()
        {
            Console.WriteLine("Text3");
        }
        public static void Text4(string name,[CallerFilePath]string filepath="",[CallerLineNumber]int num=10,[CallerMemberName]string filename="")
        {
            Console.WriteLine("Text4");
            Console.WriteLine(name+filepath+num+filename);
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _002特性
{
    /*1.特性类尾缀加上Attribute
     2.必须引用特性[AttributeUsage]并继承于System.Attribute
     3.特性内一般只有属性,没有方法
     4.构造函数内可以添加参数
         */
    [AttributeUsage(AttributeTargets.Class)]
    class MyTextAttribute:System.Attribute
    {
        private string name;
        private int id;

        public string Name { get => name; set => name = value; }
        public int Id { get => id; set => id = value; }

        public MyTextAttribute(string name)
        {
            this.Name = name;
        }
    }
}

 

莫说我穷的叮当响,大袖揽清风。 莫讥我困时无处眠,天地做床被。 莫笑我渴时无美酒,江湖来做壶。
posted @ 2018-12-04 10:33  白染  阅读(164)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3