C#特性(Attribute)之预定义特性(Conditional)

特性(Attribute)是用于在运行时传递程序中各种元数据(类、方法、结构、枚举、组件)的行为性声明标签。

特性用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。

.NET 框架提供了两种类型的特性:预定义特性和自定义特性。

Net 框架提供了三种预定义特性:

  • Conditional  这个预定义特性标记了一个条件方法,其执行依赖于他的预处理标识符。

//可以注释#define指令看看效果。

#define TRACE_ON
using System;
using System.Diagnostics;
public class Trace
{
    [Conditional("TRACE_ON")]
    public static void Msg(string msg)
    {
        Console.WriteLine(msg);
    }
}
public class ProgramClass
{
    static void Main()
    {
        Trace.Msg("Now in Main...");
        Console.WriteLine("Done.");
        Console.ReadKey();
    }
}

  • Obsolete   这个预定义标记了不应被使用的程序实体。

         参数 message,是一个字符串,描述项目为什么过时的原因以及该替代使用什么。

         参数 iserror,是一个布尔值。如果该值为 true,编译器应把该项目的使用当作一个错误。

                                                        默认值是 false(编译器生成一个警告)。

         

using System;
public class MyClass
{
    [Obsolete("Don't use OldMethod, use NewMethod instead", true)]
    static void OldMethod()
    {
        Console.WriteLine("It is the old method");
    }
     [Obsolete("Don't use OldMethod, use NewMethod instead", false)]
    static void NewMethod()
    {
        Console.WriteLine("It is the new method");
    }
    public static void Main()
    {
        OldMethod();
        NewMethod();
        Console.ReadKey();
    }
}

        AttributeUsage 

http://www.cnblogs.com/stzyw/archive/2005/10/07/249693.html

http://www.w3cschool.cc/csharp/csharp-attribute.html














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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值