Get the name of a method using an expression

后端 未结 6 1219
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 12:03

I know there are a few answers on the site on this and i apologize if this is in any way duplicate, but all of the ones I found does not do what I am trying to do.

I

6条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 12:41

    If your application would allow a dependency on Moq (or a similar library), you could do something like this:

    class Program
    {
        static void Main(string[] args)
        {
            var methodName = GetMethodName(x => new Action(x.DoSomething));
            Console.WriteLine(methodName);
        }
    
        static string GetMethodName(Func func) where T : class
        {
            // http://code.google.com/p/moq/
            var moq = new Mock();
            var del = func.Invoke(moq.Object);
            return del.Method.Name;
        }
    }
    
    public interface IMyInteface
    {
        void DoSomething(string param1, string param2);
    }
    

提交回复
热议问题