2008-11-04 2 views
0

포스트 샤프의 클래스에있는 모든 메소드에서 널 참조를 검사하는 aspect를 작성하는 방법.포스트 클래스에서 클래스의 모든 메소드에 대해 null 참조를 검사하는 aspect를 작성하는 방법

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 
     } 
    } 
} 

당신이 postsharp와 AOP에 나에게 startet을 얻기 위해 나에게 이것에 구현 샘플을 줄 수 있다면 나는 감사합니다. 다음

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

전화 :

답변

3

다른 방법은 확장 방법이다

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

T : class pervents 우리에게 실수로 복싱의 int 등

다시 AOP; Jon Skeet은 here과 비슷한 샘플을 가지고 있지만 단일 메소드/매개 변수를 다루고 있습니다.

다음은 재생 된 모습입니다. 이 측면은 한 번에 하나의 인수 만 다루고 메서드에 따라 다르지만 일반적으로 나는 이것이 완벽하게 합리적이라고 주장 할 것입니다. 그러나 아마 당신은 그것을 변경할 수 있습니다.

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); 
      } 
     } 
    } 
}