2012-01-26 49 views
7

我想實現以下模式功能:從表達式樹中提取方法名稱?

MethodInfo GetMethod(  
    Expression<Func<TTarget, EventHandler<TEventArgs>>> method) 

如果需要,我可以提供t目標的一個實例

所需的用法是:

public static void Main(string[] args) 
{ 
    var methodInfo = GetMethod<Program, EventArgs>(t => t.Method); 
    Console.WriteLine("Hello, world!"); 
} 

private void Method(object sender, EventArgs e) 
{ 
} 

這裏是我已經試過到目前爲止:

private static MethodInfo GetMethod(TTarget target, Expression<Func<TTarget, EventHandler<TEventArgs>>> method) 
{ 
    var lambda = method as LambdaExpression; 
    var body = lambda.Body as UnaryExpression; 
    var call = body.Operand as MethodCallExpression; 
    var mInfo = call.Method as MethodInfo; 

    Console.WriteLine(mInfo); 

    throw new NotImplementedException(); 
} 

它打印出來:

System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.Met hodInfo)

+0

使用您正在使用的編程語言標記問題可能會有幫助。它看起來像C#,但我不能確定。 – styfle

回答

5

你走了一半。 看下面的代碼

public static void Main(string[] args) 
{ 
    var program = new Program(); 
    var methodInfo = GetMethod<Program, EventArgs>(()=> program.Method); 
    Console.WriteLine(methodInfo.Name); 
} 

並使用下面的代碼來獲取方法名稱。

static MethodInfo GetMethod<TTarget, TEventArgs>(Expression<Func<EventHandler<TEventArgs>>> method) where TEventArgs:EventArgs 
{ 
    var convert = method.Body as UnaryExpression; 
    var methodCall = (convert.Operand as MethodCallExpression); 
    if (methodCall != null && methodCall.Arguments.Count>2 && methodCall.Arguments[2] is ConstantExpression) 
    { 
     var methodInfo = (methodCall.Arguments[2]as ConstantExpression).Value as MethodInfo; 
     return methodInfo; 
    } 
    return null; 
} 

我希望這能回答你的問題。

+0

謝謝。那樣做了! – Shimmy

相關問題