2013-03-26 1 views
0

WinRT의 작업에서 메서드 이름을 가져 오려고하는데, 여기서 Action.Method를 사용할 수 없습니다. 지금까지이있다 :WinRT의 작업에서 메서드 이름을 가져 오는 방법

public class Test2 
{ 
    public static Action<int> TestDelegate { get; set; } 

    private static string GetMethodName(Expression<Action<int>> e) 
    { 
     Debug.WriteLine("e.Body.NodeType is {0}", e.Body.NodeType); 
     MethodCallExpression mce = e.Body as MethodCallExpression; 
     if (mce != null) 
     { 
      return mce.Method.Name; 
     } 
     return "ERROR"; 
    } 

    public static void PrintInt(int x) 
    { 
     Debug.WriteLine("int {0}", x); 
    } 

    public static void TestGetMethodName() 
    { 
     TestDelegate = PrintInt; 
     Debug.WriteLine("PrintInt method name is {0}", GetMethodName(x => PrintInt(x))); 
     Debug.WriteLine("TestDelegate method name is {0}", GetMethodName(x => TestDelegate(x))); 
    } 
} 

내가 TestGetMethodName를 호출 할 때() 나는이 출력 얻을 :

e.Body.NodeType is Call 
PrintInt method name is PrintInt 
e.Body.NodeType is Invoke 
TestDelegate method name is ERROR 

목표는 TestDelegate에 할당 된 메소드의 이름을 취득하는 것입니다. "GetMethodName (x => PrintInt (x))"호출은 내가 적어도 부분적으로 올바르게하고 있음을 증명하기 위해서만 존재합니다. 어떻게하면 "TestDelegate 메서드 이름이 PrintInt"인지 알 수 있습니까?

답변

3

답변은 내가 만든 것보다 훨씬 간단합니다. 그것은 단순히 TestDelegate.GetMethodInfo()입니다. Name. GetMethodName 함수가 필요 없습니다. 나는 "System.Reflection"을 사용하지 않았기 때문에 Delegate.GetMethodInfo가 intellisense에 나타나지 않아서 어떻게 든 문서에서 찾지 못했습니다. 격차 해소를 위해 HappyNomad에게 감사드립니다.

public class Test2 
{ 
    public static Action<int> TestDelegate { get; set; } 

    public static void PrintInt(int x) 
    { 
     Debug.WriteLine("int {0}", x); 
    } 

    public static void TestGetMethodName() 
    { 
     TestDelegate = PrintInt; 
     Debug.WriteLine("TestDelegate method name is {0}", TestDelegate.GetMethodInfo().Name); 
    } 
} 
1
private static string GetMethodName(Expression<Action<int>> e) 
{ 
    Debug.WriteLine("e.Body.NodeType is {0}", e.Body.NodeType); 
    MethodCallExpression mce = e.Body as MethodCallExpression; 
    if (mce != null) { 
     return mce.Method.Name; 
    } 

    InvocationExpression ie = e.Body as InvocationExpression; 
    if (ie != null) { 
     var me = ie.Expression as MemberExpression; 
     if (me != null) { 
      var prop = me.Member as PropertyInfo; 
      if (prop != null) { 
       var v = prop.GetValue(null) as Delegate; 
       return v.Method.Name; 
      } 
     } 
    } 
    return "ERROR"; 
} 
+0

감사합니다,하지만 Delegate.Method는 WinRT에 존재하지 않습니다

작업 코드입니다. 하지만 코드를 가지고 놀면서 나는 처음부터 필요한 모든 Delegate.GetMethodInfo()를 발견했습니다. – mkelly4ca

관련 문제