如何创建一个方面检查的所有方法在一个类中postsharp空引用 [英] How to create an aspect checking for null references on all methods in a class in postsharp
问题描述
如何创建一个方面检查上一类postsharp所有方法空引用。
How to create an aspect checking for null references on all methods in a class in 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]应该然后展开以下code:
The aspect [MethodParameterNullCheck] should then unfold to the following code:
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
}
}
}
我会AP preciate,如果你能给我这个示例实现,让我startet对AOP与postsharp。
I will appreciate if you can give me a sample implementation on this to get me startet on AOP with postsharp.
推荐答案
另一种方法是一个扩展方法:
An alternative approach is an extension method:
public static void ThrowIfNull<T>(this T obj, string parameterName) where T : class
{
if(obj == null) throw new ArgumentNullException(parameterName);
}
然后调用:
foo.ThrowIfNull("foo");
bar.ThrowIfNull("bar");
在 T:类
pervents我们意外拳击整型等
The T : class
pervents us accidentally boxing ints etc.
重新AOP;乔恩斯基特有类似的东西<一个样本href="http://msmvps.com/blogs/jon_skeet/archive/2008/03/27/postsharp-and-iterator-blocks-a-beautiful-combination.aspx"相对=nofollow>此处 - 但涵盖了一个方法/参数
Re AOP; Jon Skeet has a sample for something similar here - but covering a single method/parameter.
下面是转载的方面;注意,这方面只覆盖一次一个说法,并且是方法而异,但一般我认为这是完全合理的。不过,你也许可以改变它。
Here's the aspect reproduced; note that this aspect covers only 1 argument at a time, and is method-specific, but in general I'd argue that this is perfectly reasonable... however, you could probably change it.
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);
}
}
}
}
这篇关于如何创建一个方面检查的所有方法在一个类中postsharp空引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!