gpt4 book ai didi

LINQ 是否可以通过 LINQ 表达式树获取没有返回类型的方法名称?

转载 作者:行者123 更新时间:2023-12-01 06:22:38 25 4
gpt4 key购买 nike

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

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

---> 结果:“GetUser”

最佳答案

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

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

关于LINQ 是否可以通过 LINQ 表达式树获取没有返回类型的方法名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1524290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com