从属性中更改方法的行为

本文关键字:方法 从属性 | 更新日期: 2023-09-27 18:04:23

我想从属性中改变方法的行为。考虑以下伪代码:

public class CheckHoliday : System.Attribute
{
    //Here I want exit from consumer method if today is holiday 
}
public class TestClass{
    [CheckHoliday]
    public void TestMethod(){
    }
}

我不想使用面向方面的

从属性中更改方法的行为

这个问题对我来说也不清楚,但如果这是你想要实现的,那么就有一个全局变量的解决方案。虽然它什么也不做,只是预先计算假期。

//Declare a global variable
public Boolean IsHoliday = false;
//Attribute 
public class CheckHoliday : System.Attribute
{
    //Here I want exit from consumer method if today is holiday ?
    //this ain't possible 
    public CheckHoliday()
    {
        //if  today is holiday  make IsHoliday= true based on logic
        IsHoliday= true;
        //Else keep it false
    }
}
public class TestClass
{
    [CheckHoliday]
    public void TestMethod()
    {
       //Here you can exit  if today is holiday
        if (IsHoliday)
            return;
        //Else Method Logic here
    }
}

这样做怎么样?虽然不美观,但会根据方法是否具有属性…来改变行为。

namespace Behave
{
    using System;
    using System.Reflection;
    public class CheckHolidayAttribute : Attribute { }
    class Program
    {
        static void Main(string[] args)
        {
            SomeAction();
            Console.Read();
        }
        //[CheckHoliday] // uncomment this to see what happens
        public static void SomeAction()
        {
            if(MethodInfo.GetCurrentMethod().GetCustomAttribute<CheckHolidayAttribute>() != null)
            {
                Console.WriteLine("Has attr");
            }
            else
            {
                Console.WriteLine("Does not have attr");
            }
        }
    }
}