【问题标题】:LINQ Is it possible to get a method name without a return type via LINQ expression trees?LINQ 是否可以通过 LINQ 表达式树获取没有返回类型的方法名称?
【发布时间】:2009-10-06 16:43:39
【问题描述】:

我知道可以检索具有返回类型的属性名称或方法。但是是否也可以通过 LINQ 表达式树获取没有返回类型的方法名称?

示例:字符串方法名 = GetMethodname(x=>x.GetUser());

---> 结果:“GetUser”

【问题讨论】:

    标签: linq tree get properties expression


    【解决方案1】:

    当然 - 但您需要这样的方法签名:

    public static string GetMethodName<T>(Expression<Action<T>> action)
    

    (这意味着您需要在调用它时指定类型参数,以便使用 lambda 表达式。)

    示例代码:

    using System;
    using System.Linq.Expressions;
    
    class Test
    {
        void Foo()
        {
        }
    
        static void Main()
        {
            string method = GetMethodName<Test>(x => x.Foo());
            Console.WriteLine(method);
        }
    
        static string GetMethodName<T>(Expression<Action<T>> action)
        {
            MethodCallExpression methodCall = action.Body as MethodCallExpression;
            if (methodCall == null)
            {
                throw new ArgumentException("Only method calls are supported");
            }
            return methodCall.Method.Name;
        }
    }
    

    【讨论】:

    • 从指定类型获取方法名怎么样?即表达式>>?
    • @Shimmy:说实话,你的意思并不是很清楚。可能值得提出一个新问题?
    • 我想要这个函数:static MethodInfo GetMethod(Expression&lt;Func&lt;TTarget, EventHandler&lt;TEventArgs&gt;&gt;&gt; method), here 是我迄今为止尝试过的,但它返回Delegate.CreateDelegate 方法。
    【解决方案2】:

    你需要这样的方法:

    public static string GetMethodName<T>(Expression<Action<T>> expression) {
        if (expression.NodeType != ExpressionType.Lambda || expression.Body.NodeType != ExpressionType.Call)
            return null;
        MethodCallExpression methodCallExp = (MethodCallExpression) expression.Body;
        return methodCallExp.Method.Name;
    }
    

    这样调用:GetMethodName&lt;string&gt;(s =&gt; s.ToLower()) 将返回“ToLower”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 2022-06-15
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多