我可以在运行时使用属性有条件地控制方法调用吗

我可以在运行时使用属性有条件地控制方法调用吗

本文介绍了我可以在运行时使用属性有条件地控制方法调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于我可以在运行时使用属性有条件地控制方法调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:32