如何在postsharp中为类中的所有方法创建方面检查空引用

如何在postsharp中为类中的所有方法创建方面检查空引用。

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace test { [MethodParameterNullCheck] internal class Class { public Class() { } public void MethodA(int i, ClassA a, ClassB b) { //Some business logic } } } 

然后,方面[MethodParameterNullCheck]应展开到以下代码:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace test { [MethodParameterNullCheck] internal class Class { public Class() { } public void MethodA(int i, ClassA a, ClassB b) { if (a == null) throw new ArgumentNullException("Class->MethodA: Argument a of ClassA is not allowed to be null."); if (b == null) throw new ArgumentNullException("Class->MethodA: Argument b of ClassB is not allowed to be null."); // Some Business Logic } } } 

如果你能给我一个关于这个的示例实现,我会很感激,让我通过postharp开始使用AOP。

另一种方法是扩展方法:

 public static void ThrowIfNull(this T obj, string parameterName) where T : class { if(obj == null) throw new ArgumentNullException(parameterName); } 

然后打电话:

 foo.ThrowIfNull("foo"); bar.ThrowIfNull("bar"); 

T : class意外地击败我们拳击等。

Re AOP; Jon Skeet 在此处提供了类似的示例 – 但涵盖了单个方法/参数。

这是再现的方面; 请注意,这个方面一次只涵盖一个参数,并且是特定于方法的,但总的来说我认为这是完全合理的……但是,你可能会改变它。

 using System; using System.Reflection; using PostSharp.Laos; namespace IteratorBlocks { [Serializable] class NullArgumentAspect : OnMethodBoundaryAspect { string name; int position; public NullArgumentAspect(string name) { this.name = name; } public override void CompileTimeInitialize(MethodBase method) { base.CompileTimeInitialize(method); ParameterInfo[] parameters = method.GetParameters(); for (int index = 0; index < parameters.Length; index++) { if (parameters[index].Name == name) { position = index; return; } } throw new ArgumentException("No parameter with name " + name); } public override void OnEntry(MethodExecutionEventArgs eventArgs) { if (eventArgs.GetArguments()[position] == null) { throw new ArgumentNullException(name); } } } }