【C#】特性的基本操作

主函数:
#define IsTest
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;


namespace 特性
{
    class Program
    {
        //Obsolete特性,第一个参数的string编译器将会显示给用户
        [Obsolete("这个方法被弃用了,使用newMethod代替")]//第二个bool参数可设置函数是否可用
        static void oldMethod()
        {

        }
        static void newMethod()
        {

        }


        //Conditional特性
        [Conditional("IsTest")] //只有定义了IsTest宏,才会调用test1函数
        static void test()
        {

        }
        //DebuggerStepThrough特性
        [DebuggerStepThrough]  //函数可以跳过调试阶段,当确定函数无BUG时使用
        static void test1()
        {

        }

        [Serializable] //声明结构可以被序列化  相反的特性为:[NonSerializable]不可被序列化
        static void test2()
        {

        }
        [MyTest]  //自定义的特性
        static void test3()
        {

        }

        static void Main(string[] args)
        {
            oldMethod();
        }
    }
}
自定义特性类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 特性
{
    //自定义特性类一般以Attribute结尾
    //需要继承自System.Attribute
    //一般情况申明为sealed
    //一般情况下用来表示目标结构的一些状态(定义一些字段属性)
    [AttributeUsage(AttributeTargets.Class)]//表示该特性类可以应用到的程序结构 如委托,事件等
    sealed class MyTestAttribute : System.Attribute
    {
        public string Des { get; set; }
        public string Version { get; set; }
        public int ID { get; set; }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值