Fast ArgumentNullException with attributes. It is possible?
Is there any fast way to verify null arguments via attributes or something?
Convert this:
public void Method(t开发者_如何学运维ype arg1,type arg2,type arg3)
{
if (arg1== null) throw new ArgumentNullException("arg1");
if (arg2== null) throw new ArgumentNullException("arg2");
if (arg3== null) throw new ArgumentNullException("arg3");
//Business Logic
}
Into something like this:
[VerifyNullArgument("arg1","arg2","arg3")]
public void Method(type arg1,type arg2,type arg3)
{
//Business Logic
}
Ideas? thanks guys.
There are Code Contracts built into .NET 4. That's probably as close as you'll get. There's quite a bit more information at DevLabs if you chose to go this route.
You're looking for PostSharp.
not an attribute, but similar idea:
class SomeClass
{
public static void VerifyNullArgument(params object objects)
{
if (objects == null)
{
throw new ArgumentNullException("objects");
}
for (int index = 0; index < objects.Lenght; index++)
{
if (objects[index] == null)
{
throw new ArgumentException("Element is null at index " + index,
"objects");
}
}
}
}
then in your example method
public void Method(type arg1,type arg2,type arg3)
{
SomeClass.VerifyNullArgument(arg1, arg2, arg3);
//Business Logic
}
精彩评论