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

本文关键字:方法 调用 基类 何使用 PostSharp | 更新日期: 2023-09-27 17:58:05

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

调用ToString时,如何才能调用OnInvoke

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

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

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