从属性更改方法的行为

时间:2015-07-23 05:15:45

标签: c#

我想从属性更改方法的行为。 考虑这个伪代码:

remove

我不想使用面向方面。

2 个答案:

答案 0 :(得分:1)

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

//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

    }
}

答案 1 :(得分:0)

这个怎么样,不优雅,但会根据方法是否具有属性来改变行为......

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");
            }
        }
    }
}