Tôi cố gắng để thực hiện chức năng mô hình sau:Trích xuất tên phương thức từ cây biểu thức?
MethodInfo GetMethod(
Expression<Func<TTarget, EventHandler<TEventArgs>>> method)
tôi có thể cung cấp một thể hiện của TTarget nếu cần
Việc sử dụng mong muốn là:
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)
{
}
Đây là những gì tôi đã cố gắng cho đến nay:
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();
}
Nó in ra:
System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.Met hodInfo)
Có thể hữu ích khi gắn thẻ câu hỏi bằng ngôn ngữ lập trình bạn đang sử dụng. Có vẻ như C# nhưng tôi không thể chắc chắn. – styfle