2014-10-06 4 views
3

매개 변수를 얻는 방법 NAMES 메서드입니다. 예를 들어 값을으로 설정하고 NAMES을 설정하지 않는 방법을 보여줍니다. 나는 = 파 르 마 = 99, parmb을보고 1 단지 99, 1매개 변수 이름 가져 오기

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 
    using System.Diagnostics; 
    using PostSharp.Aspects; 

    namespace GettingParmNames 
    { 
     public class Program 
     { 
      static void Main(string[] args) 
      { 
       Foo myfoo = new Foo(); 
       int sum = myfoo.DoA(99, 1); 
       Console.WriteLine(sum.ToString()); 

       Console.ReadKey(); 
      } 
     } 

    public class Foo 
    { 
     [ExceptionAspect] 
     public int DoA(int parma, int parmb) 
     { 
      int retVal; 
      try 
      { 
       retVal = parma + parmb; 
       if (parma == 99) 
       { 
        throw new Exception("Fake Exception"); 
       } 

      } 
      catch (Exception ex) 
      { 
       retVal = -1; 
       throw new Exception("There was a problem"); 
      } 

      return retVal; 
     } 
    } 

    [Serializable] 
    public class ExceptionAspect : OnExceptionAspect 
    { 
     public override void OnException(MethodExecutionArgs args) 
     { 
      string parameterValues = ""; 

      foreach (object arg in args.Arguments) 
      { 
       if (parameterValues.Length > 0) 
       { 
        parameterValues += ", "; 
       } 

       if (arg != null) 
       { 
        parameterValues += arg.ToString(); 
       } 
       else 
       { 
        parameterValues += "null"; 
       } 
      } 

      Console.WriteLine("Exception {0} in {1}.{2} invoked with arguments {3}", args.Exception.GetType().Name, args.Method.DeclaringType.FullName, args.Method.Name, parameterValues); 
     } 
    } 

} 
+1

코드 변수 이름을 가져 오시겠습니까? '파마'를 프린트하고 싶습니까? 아니면 파마가 무엇이든 상관없이 출력 해 주길 원합니까? – Ideasthete

답변

4

당신은 args.Method.GetParameters()를 호출하여 OnException 방법에 메소드 매개 변수 '정보에 액세스 할 수 있습니다하지합니다. 그러나 일반적으로 성능상의 이유로 컴파일 시간 동안 데이터를 초기화하는 것이 더 좋습니다 - CompileTimeInitialize 메서드 재정의.

[Serializable] 
public class ExceptionAspect : OnExceptionAspect 
{ 
    private string[] parameterNames; 

    public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) 
    { 
     parameterNames = method.GetParameters().Select(p => p.Name).ToArray(); 
    } 

    public override void OnException(MethodExecutionArgs args) 
    { 
     StringBuilder parameterValues = new StringBuilder(); 

     for (int i = 0; i < args.Arguments.Count; i++) 
     { 
      if (parameterValues.Length > 0) 
      { 
       parameterValues.Append(", "); 
      } 

      parameterValues.AppendFormat(
       "{0} = {1}", parameterNames[i], args.Arguments[i] ?? "null"); 
     } 

     // ... 
    } 
+0

정말 고맙습니다. – dannyrosalex