2009-08-07 21 views
1

.NET中的Conditional Attribute允許您在編譯時禁用方法的調用。我正在尋找基本上相同的東西,但在運行時。我覺得在AOP框架中應該存在這樣的事情,但我不知道這個名字,所以我很難弄清楚它是否被支持。我可以在運行時使用屬性有條件地控制方法調用嗎?

因此,作爲一個例子,我想這樣做

[RuntimeConditional("Bob")] 
public static void M() { 
    Console.WriteLine("Executed Class1.M"); 
} 

//..... 

//Determines if a method should execute. 
public bool RuntimeConditional(string[] conditions) { 
    bool shouldExecute = conditions[0] == "Bob"; 

    return shouldExecute; 
} 

那麼,曾經在代碼中存在對中號方法的調用,它會首先調用RuntimeConditional並傳遞Bob來確定是否應該執行M

+0

在你的例子中,什麼樣的代碼會讓M執行?什麼樣的代碼會使它不能執行,你會期望發生什麼? – Stobor 2009-08-07 01:46:03

+0

RuntimeConditional方法將控制它是否會執行。現在鮑勃是硬編碼的,所以它會一直執行。 RuntimeConditional方法中的字符串Bob將被替換爲一些代碼以從配置文件/數據庫字段中拉取以查看該方法是否應該被調用。 – Bob 2009-08-07 01:48:41

+0

您可以簡單地在Trace屬性的OnEntry覆蓋中引發異常。不完全是你要找的東西,但它會阻止你的方法執行。 – 2009-08-07 05:37:49

回答

5

實際上,你可以使用PostSharp做你想做什麼。

這裏有一個簡單的例子,你可以使用:

[Serializable] 
public class RuntimeConditional : OnMethodInvocationAspect 
{ 
    private string[] _conditions; 

    public RuntimeConditional(params string[] conditions) 
    { 
     _conditions = conditions; 
    } 

    public override void OnInvocation(MethodInvocationEventArgs eventArgs) 
    { 
     if (_conditions[0] == "Bob") // do whatever check you want here 
     { 
      eventArgs.Proceed(); 
     } 
    } 
} 

或者,因爲你只是希望在方法執行「之前」,你可以使用OnMethodBoundaryAspect

[Serializable] 
public class RuntimeConditional : OnMethodBoundaryAspect 
{ 
    private string[] _conditions; 

    public RuntimeConditional(params string[] conditions) 
    { 
     _conditions = conditions; 
    } 

    public override void OnEntry(MethodExecutionEventArgs eventArgs) 
    { 
     if (_conditions[0] != "Bob") 
     { 
      eventArgs.FlowBehavior = FlowBehavior.Return; // return immediately without executing 
     } 
    } 
} 

如果您方法有返回值,你也可以處理它們。 eventArgs有一個可設置的returnValue屬性。

+0

甜,謝謝! FlowBehavior是我想要的 – Bob 2009-08-07 10:10:43

+0

很酷。雖然我只是意識到我把邏輯搞砸了 - 如果條件*不符合,你想要FlowBehaviour.Return。 – 2009-08-07 11:24:51

0

我相信這將是你所描述的做的一個非常簡單的方法:

public static void M() 
{ 
    if (RuntimeConditional("Bob")) 
    { 
     Console.WriteLine("Executed Class1.M"); 
    } 
} 

感謝

+0

是的,雖然沒有使用屬性。 – Bob 2009-08-07 01:33:51

相關問題