问题描述
我在C#中创建了一个方法>获取方法名
I created a method in C# to get methodname
public string GetCorrectPropertyName<T>(Expression<Func<T, string>> expression)
{
return ((MemberExpression)expression.Body).Member.Name; // Failure Point
}
并将其称为
string lcl_name = false;
public string Name
{
get { return lcl_name ; }
set
{
lcl_name = value;
OnPropertyChanged(GetCorrectPropertyName<ThisClassName>(x => x.Name));
}
}
如果属性是字符串,并且所有其他类型给出了这个例外:
This works fine if property is string and for all other types gives this exception:
- 我在方法签名中将字符串更改为对象,但是再次失败。 / li>
- 我从
x => x.PropertyName
tox => Convert.ToString(x.PropertyName)
并且仍然失败
- 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?
推荐答案
您需要单独的一行来提取输入表达式是Unary Expression的Member。
You need a separate line to extract the Member where the input expression is a Unary Expression.
刚刚从VB.Net转换了这个,所以可能会稍微关闭 - 让我知道如果我需要做任何微调:
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;
}
}
VB版本是:
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”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!