item) { return ((MemberExpression)-6ren">
gpt4 book ai didi

c# - 错误信息 "Operator ' .' cannot be applied to operand of type ' lambda expression '"when converting a method to Extension Method?

转载 作者:太空狗 更新时间:2023-10-29 18:13:35 24 4
gpt4 key购买 nike

我有一个方法想转换为扩展方法

public static string GetMemberName<T>(Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}

并称它为

string str = myclass.GetMemberName(() => new Foo().Bar); 

所以它的计算结果为 str = "Bar";//它给出了成员名称而不是它的值

现在当我尝试通过这个将其转换为扩展方法时

public static string GetMemberName<T>(this Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}

并称它为

string str = (() => new Foo().Bar).GetMemberName();

错误提示 Operator '.'不能应用于“lambda 表达式”类型的操作数

我哪里错了?

最佳答案

这里真的有两件事,第一,通过() => new Foo().Bar进入接受 Expression<Func<T>> 的方法将指定的表达式树视为 Expression<Func<T>> ,但是() => new Foo().Bar不是 Expression<Func<T>>靠自己。

其次,为了让您的扩展方法接受任何 lambda(例如您提供的),您必须使用与任何表达式树相对应的类型。但是,正如您可能已经根据消息 ... to operand of type 'lambda expression' 猜到的那样您通常会在引号内看到类型名称的地方,即 lambda 表达式被语言特殊处理,这使得您在不先强制转换的情况下尝试做的事情是不可能的。

以扩展方法形式调用扩展方法的方式是(在 Barstring 类型的情况下)

((Expression<Func<string>>)(() => new Foo().Bar)).GetMemberName()` 

这似乎并不是那么理想。

关于c# - 错误信息 "Operator ' .' cannot be applied to operand of type ' lambda expression '"when converting a method to Extension Method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11167676/

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