Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c# - Extract method name from expression tree?

I am trying to implement the following pattern function:

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

I can provide an instance of TTarget if required

The desired usage is:

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

Here's what I've tried so far:

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

It prints out:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're half way there. Look at the code below

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

And use the following code to get the method 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;
}

I hope this answers your question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...