[英]What is the difference between Member Expressions and an Expression Tree Generated by a Lambda?
This title might not actually make sense, because these things might be entirely different. 这个标题可能实际上没有任何意义,因为这些东西可能完全不同。 First, let me explain why I'm trying to learn about this:
首先,让我解释一下为什么要尝试了解这一点:
I'm currently trying to write a unit test for a method that touches a lot of properties. 我目前正在尝试为一种涉及很多属性的方法编写单元测试。 Due to that, I'd prefer to write a test that takes in a list of property names as its member data and that will not start randomly failing if someone goes and changes the name of the property.
因此,我更愿意编写一个将属性名称列表作为其成员数据的测试,并且如果有人去更改属性名称,该测试将不会随机失败。 At first, I started with string reflection, but I knew that's a bad idea as it fails that second caveat.
最初,我从字符串反射开始,但是我知道这是个坏主意,因为它没有第二次警告。
That led me to the following thread and the following code: C# Reflection - Get PropertyInfo without a string 这导致我进入以下线程和以下代码: C#反射-不带字符串的Get PropertyInfo
public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name;
}
This works well with GetValue(), but now I'm trying to understand it. 这与GetValue()一起很好地工作,但是现在我试图理解它。 I think I understand how the Expression class basically takes apart the expression lambda and builds a class from it, but I'm trying to understand what the MemberExpression really is and what the difference is with it that allows me to access the name of a class property.
我想我了解Expression类基本上是如何分解lambda表达式并从中构建一个类的,但是我试图了解MemberExpression的真正含义,以及与它的区别是什么,它使我可以访问类的名称属性。 I apologize if I'm way off track here.
如果我不在这里,我深表歉意。
a MemberExpression
is an expression that allows you to access the members of an instance, be a field or a property. MemberExpression
是一个表达式,允许您访问实例的成员,可以是字段或属性。 It stores the information needed to retrieve that member, such as the host class, member name and type. 它存储检索该成员所需的信息,例如主机类,成员名称和类型。
Here is the content of FieldMember and PropertyMember : 这是FieldMember和PropertyMember的内容:
Screenshot generated from LINQPad .Dump()
. 从LINQPad
.Dump()
生成的屏幕截图。
Source : 资源 :
void Main()
{
GetPropertyName<Foo, string>(f => f.Bar);
GetPropertyName<Foo, string>(f => f.bar);
}
// Define other methods and classes here
public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
expression.Dump();
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name;
}
public class Foo
{
public string Bar { get; set; }
public string bar;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.