【问题标题】:Postsharp Newbie - Why is args.Instance null?Postsharp Newbie - 为什么 args.Instance 为空?
【发布时间】:2011-07-04 01:39:07
【问题描述】:

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

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");
    }
}

【问题讨论】:

  • 你明白了吗?

标签: aop postsharp


【解决方案1】:

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

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/

【讨论】:

  • [Serializable] 唉,那不行。我在乱搞代码,把 locationboundary 留在了。 public class AuthorizeActivityAttribute : OnMethodBoundaryAspect 上面的编辑代码............
  • 更新了我的答案。这是 PostSharp 通过检查您是否使用特定属性来使用的优化。如果没有,它不会打扰初始化它们。
  • 人力资源部。就我而言,我正在使用它——大多数时候它是非空的,但有时是空的...... WTF?
  • 哇!当方法为静态时,实例为空。 :::叹息:::
猜你喜欢
  • 1970-01-01
  • 2013-10-30
  • 2015-06-30
  • 2016-07-11
  • 2012-12-17
  • 2013-09-21
  • 2012-02-15
  • 1970-01-01
  • 2020-08-22
相关资源
最近更新 更多