Postsharp 新手 - 为什么 args.Instance 为空? [英] Postsharp Newbie - Why is args.Instance null?

查看:17
本文介绍了Postsharp 新手 - 为什么 args.Instance 为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PostSharp 新手 --- 我现在正在尝试 NuGet 版本,并且我正在尝试了解 AuthoriseAttribute OnEntry 方法中的 wny,即 agrs.Instance 值为 null.我正在尝试实现取决于对象值的授权,例如已存档的客户无法提高信用额度.我正在其他特定于规则的类中实施规则.

New to PostSharp --- I'm trying out the NuGet version now and I'm trying to understand wny in the AuthoriseAttribute OnEntry method that the agrs.Instance value is null. I'm trying to implement authorsation that depends on the values of the object e.g. A customer who's been archived can't have a credit limit raised. I'm implementing the rules within other classes specific to the rules.

public class Program
{
    static void Main(string[] args)
    {
        var c = new Customer();
        c.RaiseCreditLimit(100000);
        c.Error(00); 
    }
}

public class Customer
{
    [AuthorizeActivity]
    public void RaiseCreditLimit(int newValue)
    {
    }

    [AuthorizeActivity]
    public void Error(int newValue)
    {

    }
}

[Serializable]
public class AuthorizeActivityAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        //
        //Why is args.Instance null???????????
        //
        if (args.Method.Name == "RaiseCreditLimit")
        {
            Debug.WriteLine(args.Method.Name + " started");
        }
        else
        {
            throw new Exception("Crap");
        }
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        Debug.WriteLine(args.Method.Name + " finished");
    }
}

推荐答案

答案是因为你没有在你的方面使用它.这是一个优化.如果您在方面中使用它,那么它将被设置.更改您的方面以使用实例,它就会在那里.

The answer is because you're not using it in your aspect. It's an optimization. If you use it in the aspect then it will be set. Change your aspect to consume instance and it will be there.

public override void OnEntry(MethodExecutionArgs args)
        {
            //
            //Why is args.Instance null???????????
            //
            if (args.Method.Name == "RaiseCreditLimit")
            {
                Debug.WriteLine(args.Instance.GetType().Name);
                Debug.WriteLine(args.Method.Name + " started");
            }
            else
            {
                throw new Exception("Crap");
            }
        }

有关更多信息,请查看本文以了解 PostSharp 还为优化代码做了哪些工作 http://programmersunlimited.wordpress.com/2011/03/23/postsharp-weaving-community-vs-professional-reasons-to-get-a-professional-license/

For more info check out this article to see what else PostSharp does to optimize code http://programmersunlimited.wordpress.com/2011/03/23/postsharp-weaving-community-vs-professional-reasons-to-get-a-professional-license/

这篇关于Postsharp 新手 - 为什么 args.Instance 为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆