如何使用PostSharp拦截基类上的方法调用?

时间:2014-04-13 23:32:11

标签: c# aop postsharp

我想使用PostSharp为各种类提供System.Object.ToString的实现。我已经创建了一个继承自MethodInterceptionAspect的方面,但OnInvoke方法在调用EchoDto.ToString时无法调用。

如何在调用OnInvoke时调用ToString

[DataContract]
[ImplementJsonToStringAspect()]
public class EchoDto
{

    [DataMember]
    public string Text { get; set; }

}

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method)]
public class ImplementJsonToStringAspect : MethodInterceptionAspect
{

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        base.OnInvoke(args); // Never gets called
    }

    public override bool CompileTimeValidate(MethodBase method)
    {
        return method.Name == "ToString";
    }

}

1 个答案:

答案 0 :(得分:2)

继承InstanceLevelAspect并使用[IntroduceMember(OverrideAction=MemberOverrideAction.OverrideOrFail)]修饰方法。要在目标对象上引用this,请使用this.Instance

/// <summary>
/// Implements a ToString method on the target class that serializes the members to JSON.
/// </summary>
[Serializable]
public class ImplementJsonToStringAspect : InstanceLevelAspect
{

    #region Methods

    /// <summary>
    /// Provides an implementation of <see cref="System.Object.ToString"/> that serializes the instance's
    /// public members to JSON.
    /// </summary>
    /// <returns></returns>
    [IntroduceMember(OverrideAction=MemberOverrideAction.OverrideOrFail)]
    public override string ToString()
    {
        return JsonConvert.SerializeObject(this.Instance);
    }

    #endregion

}

注意:这需要免费版本不支持PostSharp的付费版本InstanceLevelAspect