我有一个方法想要转换为扩展方法
public static string GetMemberName<T>(Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}
并称其为
string str = myclass.GetMemberName(() => new Foo().Bar);
所以它的评估结果是str = "Bar"; // It gives the Member name and not its value
现在,当我尝试通过此方法将其转换为扩展方法时
public static string GetMemberName<T>(this Expression<Func<T>> item)
{
return ((MemberExpression)item.Body).Member.Name;
}
并称之为
string str = (() => new Foo().Bar).GetMemberName();
错误说Operator '.' cannot be applied to operand of type 'lambda expression'
我哪里错了?
这里实际上有两件事,第一,通过() => new Foo().Bar
进入接受的方法Expression<Func<T>>
将指定的表达式树视为Expression<Func<T>>
, but () => new Foo().Bar
不是一个Expression<Func<T>>
在其自己的。
其次,为了让您的扩展方法接受任何 lambda(例如您提供的),您必须使用与任何表达式树对应的类型。但是,正如您可能已经根据消息猜到的那样... to operand of type 'lambda expression'
您通常会在引号内看到类型的名称,该语言会特别对待 lambda 表达式,这使得您在不先进行强制转换的情况下尝试执行的操作是不可能的。
以扩展方法形式调用扩展方法的方法是(在这种情况下Bar
属于类型string
)
((Expression<Func<string>>)(() => new Foo().Bar)).GetMemberName()`
这似乎并不是那么理想。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)