C#特性

创建一个自定义特性:

// 描述如何使用一个自定义特性 SomethingAttribute
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]    

//********自定义特性SomethingAttribute**************//
public class SomethingAttribute : Attribute    {
    private string name; // 名字
    private string data; // 日期
    public string Name {
        get { return name; }
        set { name = value; }
    }
    public string Data    {
        get { return data; }
        set { data = value; }
    }
    public SomethingAttribute(string name)    {
        this.name = name;
        this.name = name;
    }
}

实例化定义

[Something("Amy", Data = "2018-06-18")]
[Something("Jack", Data = "2018-06-18")]
class Test{}

获取自定义特性的中的变量

Type t = typeof(Test);
var something = t.GetCustomAttributes(typeof(SomethingAttribute),true);
foreach(SomethingAttribute each in something)
{
    Console.WriteLine("Name:{0}", each.Name);
    Console.WriteLine("Data:{0}",each.Data);
}

Conditional的应用

#define BUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;


namespace helloworld
{
    public class Myclass
    {
        [Conditional("BUG")]
        public static void M1(string msg)
        {
            Console.WriteLine(msg);
        }
        [Conditional("deBUG")]
        public static void M2(string msg)
        {
            Console.WriteLine(msg);
        }
        [Conditional("BUG")]
        public static void M3(string msg)
        {
            Console.WriteLine(msg);
        }
        [Conditional("kk")]
        public static void M4(string msg)
        {
            Console.WriteLine(msg);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Myclass.M1("456");
            Myclass.M2("845");
            Myclass.M3("dadasd");
            Myclass.M4("456xcvc");
            Console.WriteLine("Main thread ID is:" );
            Console.ReadKey();
        }
    }
}

将头部的#define BUG就会运行M1和M3,定义为#define kk就将会只运行M4方法。

但是注意如果没有写[]的都会执行,所以一般加[]attrible时候,常常看见如果有加一般每个方法上面都会加。

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值