问题描述
我有一个表达式指向我的类型的属性。
但它不适用于每个属性类型。 不意味着意味着
它导致不同的表达式类型。我以为会导致
MemberExpression
,但情况并非如此。
I have a expression to point on a property of my type.But it does not work for every property type. "Does not mean" meansit result in different expression types. I thought it will ever result in aMemberExpression
but this is not the case.
code> int 和 Guid
它会导致 UnaryExpression
和 string
在 MemberExpression
。
For int
and Guid
it results in a UnaryExpression
and for string
in a MemberExpression
.
我是有点困惑;)
我的课程
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
测试代码
Person p = new Person { Age = 16, Name = "John" };
Expression<Func<Person, object>> expression1 = x => x.Age;
// expression1.Body = UnaryExpression;
Expression<Func<Person, object>> expression2 = x => x.Name;
// expression2.Body = MemberExpression;
问题
表达式并检查它们是否是平均值
相同的类型和相同的属性?
Question
How can i compare two expressions and check if they are meanthe same type and same property ?
感谢使用者带给我的用户 dasblinkenlight 在正确的轨道上。
Thanks to user dasblinkenlight who brought me on the right track.
他提供了方法
private static MemberExpression GetMemberExpression<T>(
Expression<Func<T,object>> exp
) {
var member = expr.Body as MemberExpression;
var unary = expr.Body as UnaryExpression;
return member ?? (unary != null ? unary.Operand as MemberExpression : null);
}
我写了以下扩展方法来比较 GetMemberExpression
方法,并检查 GetMemberExpression()。Member.Name
是否相同。
I wrote the following extension method to compare the results of the GetMemberExpression
methods and check if GetMemberExpression().Member.Name
are the same.
private static bool IsSameMember<T>(this Expression<Func<T, object>> expr1, Expression<Func<T, object>> expr2)
{
var result1 = GetMemberExpression(expr1);
var result2 = GetMemberExpression(expr2);
if (result1 == null || result2 == null)
return false;
return result1.Member.Name == result2.Member.Name;
}
推荐答案
年龄
是一种值类型。为了强制将一个值类型转换为 Func< Person,object>
,编译器需要插入一个,a 。
The reason this happens is that Age
is a value type. In order to coerce an expression returning a value type into Func<Person,object>
the compiler needs to insert a Convert(expr, typeof(object))
, a UnaryExpression
.
对于 string
s和其他引用类型,然而,不需要框,因此返回直成员表达式。
For string
s and other reference types, however, there is no need to box, so a "straight" member expression is returned.
如果您想要访问 UnaryExpression
中的 MemberExpression
您可以获得其操作数:
If you would like to get to the MemberExpression
inside the UnaryExpression
, you can get its operand:
private static MemberExpression GetMemberExpression<T>(
Expression<Func<T,object>> exp
) {
var member = exp.Body as MemberExpression;
var unary = exp.Body as UnaryExpression;
return member ?? (unary != null ? unary.Operand as MemberExpression : null);
}
这篇关于类型成员的表达式导致不同的表达式(MemberExpression,UnaryExpression)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!