我可以在运行时使用属性有条件地控制方法调用吗? [英] Can I conditionally control method calls at runtime with attributes?
问题描述
.NET 中的条件属性允许您在编译时禁用方法调用.我正在寻找基本相同的东西,但在运行时.我觉得 AOP 框架中应该存在这样的东西,但我不知道它的名字,所以我很难确定它是否受支持.
The Conditional Attribute in .NET allows you to disable the invocation of methods at compile time. I am looking for basically the same exact thing, but at run time. I feel like something like this should exist in AOP frameworks, but I don't know the name so I am having trouble figuring out if it is supported.
举个例子,我想做这样的事情
So as an example I'd like to do something like this
[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;
}
因此,无论在代码中调用 M 方法的任何地方,它都会首先调用 RuntimeConditional 并传入 Bob 以确定是否M 应该被执行.
So where ever in code there is a call to the M method, it would first call RuntimeConditional and pass in Bob to determine if M should be executed.
推荐答案
你实际上可以使用 PostSharp做你想做的.
You can actually use PostSharp to do what you want.
这是一个您可以使用的简单示例:
Here's a simple example you can use:
[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
:
Or, since you're just looking at "before" the method executes, you can use the 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
属性.
If your methods have return values, you can deal with them too. eventArgs
has a returnValue
property that is settable.
这篇关于我可以在运行时使用属性有条件地控制方法调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!