Attribute在编程中的应用(1)

本文通过一个C#示例介绍了如何使用ConditionalAttribute来控制方法的执行,这对于调试和日志记录非常有用。示例展示了不同的宏定义如何影响方法是否在编译时被忽略。

border="0" src="http://forum.booye.com/byhtm/1.html" frameborder="0" width="470" height="60">

#define NOBUG // C#的宏定义必须出现在所有代码之前。当前只让NOBUG宏有效。
//#define BUGED  
//#define WANG
//#define XIA

using System;
using System.Diagnostics; // 为了使用包含在此名称空间中的ConditionalAttribute特性

namespace ConsoleTest
{
    
class ToolKit
    {
        [ConditionalAttribute(
"WANG")]           // Attribute名称的长记法
        [ConditionalAttribute("BUGED")]
        
public static void Method_1() { Console.WriteLine("Created By WANG, Buged."); }

        [ConditionalAttribute(
"WANG")]
        [ConditionalAttribute(
"NOBUG")]
        
public static void Method_2() { Console.WriteLine("Created By WANG, NoBug."); }

        [Conditional(
"XIA")]                             // Attribute名称的短记法
        [Conditional("BUGED")]
        
public static void Method_3() { Console.WriteLine("Created By XIA, Buged."); }

        [Conditional(
"XIA")]
        [Conditional(
"NOBUG")]
        
public static void Method_4() { Console.WriteLine("Created By XIA, NoBug."); }
    }

    
class MClass
    {
        [STAThread]
        
static void Main(string[] args)
        {
            
//虽然方法都被调用了,但只有符合条件(有效宏)的才会被执行。
            ToolKit.Method_1();
            ToolKit.Method_2();
            ToolKit.Method_3();
            ToolKit.Method_4();

            Console.ReadLine();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值