如何使用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
?
[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屋!