且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-23 15:20:58

你实际上可以使用 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.