我想使用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";
}
}
答案 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
。