如何使用 PostSharp 拦截基类上的方法调用? [英] How do you intercept method calls on a base class using PostSharp?
问题描述
我想使用 PostSharp 为各种类提供 System.Object.ToString
的实现.我创建了一个从 MethodInterceptionAspect
继承的方面,但是当调用 EchoDto.ToString
时,OnInvoke
方法没有被调用.
I want to provide an implementation of System.Object.ToString
to various classes using PostSharp. I've created an aspect inheriting from MethodInterceptionAspect
but the OnInvoke
method isn't getting invoked when a call to EchoDto.ToString
takes place.
如何在调用 ToString
时调用 OnInvoke
?
How can I get OnInvoke
to be called when ToString
is called?
[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";
}
}
推荐答案
从 InstanceLevelAspect
继承并用 [IntroduceMember(OverrideAction=MemberOverrideAction.OverrideOrFail)]
装饰方法.要在目标对象上引用 this
,请使用 this.Instance
.
Inherit from InstanceLevelAspect
and decorate the method with [IntroduceMember(OverrideAction=MemberOverrideAction.OverrideOrFail)]
. To reference this
on the target object, use 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
.
Note: This requires the paid version of PostSharp as InstanceLevelAspect
is not supported by the free version.
这篇关于如何使用 PostSharp 拦截基类上的方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!