本文介绍了无法转换类型'System.Linq.Expressions.UnaryExpression“对象键入'System.Linq.Expressions.MemberExpression”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了C#方法>获取方法名
公共字符串GetCorrectPropertyName< T>(表达式来; Func键< T,串>>表达式)
{
回报率((MemberExpression)expression.Body).Member.Name; //故障点
}
和调用它作为
字符串lcl_name = FALSE;
公共字符串名称
{
{返回lcl_name; }
组
{
lcl_name =价值;
OnPropertyChanged(GetCorrectPropertyName< ThisClassName>(X => x.Name));
}
}
这工作正常,如果属性是字符串,并为所有其他类型给出了这样的例外:
- I changed string to object in method signature, but then it fails again.
- I changed calling from
x => x.PropertyName
tox => Convert.ToString(x.PropertyName)
and it still fails
Where am I wrong?
解决方案
You need a separate line to extract the Member where the input expression is a Unary Expression.
Just converted this from VB.Net, so might be slightly off - let me know if I need to make any minor tweaks:
public string GetCorrectPropertyName<T>(Expression<Func<T, Object>> expression)
{
if (expression.Body is MemberExpression) {
return ((MemberExpression)expression.Body).Member.Name;
}
else {
var op = ((UnaryExpression)expression.Body).Operand;
return ((MemberExpression)op).Member.Name;
}
}
The VB version is:
Public Shared Function GetCorrectPropertyName(Of T) _
(ByVal expression As Expression(Of Func(Of T, Object))) As String
If TypeOf expression.Body Is MemberExpression Then
Return DirectCast(expression.Body, MemberExpression).Member.Name
Else
Dim op = (CType(expression.Body, UnaryExpression).Operand)
Return DirectCast(op, MemberExpression).Member.Name
End If
End Function
Note that the input expression does not return string necessarily - that constrains you to only reading properties that return strings.
这篇关于无法转换类型'System.Linq.Expressions.UnaryExpression“对象键入'System.Linq.Expressions.MemberExpression”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!