Lambda 表达式未返回预期的 MemberInfo [英] Lambda expression not returning expected MemberInfo

查看:13
本文介绍了Lambda 表达式未返回预期的 MemberInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个我没想到的问题.一个例子可能比一个段落更能说明我的问题:

I'm running into a problem that I did not expect. An example will probably illustrate my question better than a paragraph:

更新:跳到最后一个代码块以获得更雄辩的代码示例.

UPDATED: Skip to last code-block for a more eloquent code example.

public class A
{
  public string B { get; set; }
}

public class C : A { }

这是一个方法的一些代码:

Here is some code from a method:

var a = typeof(C).GetMember("B")[0];
var b = typeof(A).GetMember("B")[0];

Expression<Func<C, string>> c = x => x.B;

var d = (c.Body as MemberExpression).Member;

以下是一些比较的结果:

Here are the results of some comparisons:

a == b //false
a == d //false
b == d //true

前两个有点出乎意料.我知道即使 B 不是虚拟的,C 也可以使用 w new 运算符定义一个同名的属性,但在这种情况下我没有.

The first two are somewhat unexpected. I understand that even though B is not virtual, C could define a property with the same name with thew new operator, but in this case I did not.

第二个对我来说真的是最令人惊讶的(也是我问题的核心).即使 lambda 的参数明确定义为 C 类型,它仍然返回它,就像从基类访问该属性一样.

The second is really the most surprising to me (and is the heart of my problem). Even though the parameter for the lambda is clearly defined as being of type C, it still returns it as if the property was accessed from the base class.

我正在寻找的是一种从 lambda 表达式获取 MemberInfo 的方法,就好像我使用了参数类型的反射来获取 MemberInfo.我的项目基本上将 MemberInfos 存储在各种字典中,它需要具有通过提供 lambda 表达式来访问元素的功能.

What I'm looking for is a way to get the MemberInfo from a lambda expression as if I had used reflection on the type of the parameter to get the MemberInfo. My project essentially stores MemberInfos in a dictionary of sorts and it needs to have functionality where you can access the elements by providing a lambda expression.

Danny Chen 重述的代码示例

Restated code sample by Danny Chen

public class Base
{
    public string Name { get; set; }
}
public class Derived : Base { }

//in Main
var parentMember = typeof(Base).GetMember("Name")[0];
var childMember = typeof(Derived).GetMember("Name")[0];

Expression<Func<Base, string>> parentExp = x => x.Name;
var parentExpMember = (parentExp.Body as MemberExpression).Member;

Expression<Func<Derived, string>> childExp = x => x.Name;
var childExpMember = (childExp.Body as MemberExpression).Member;

parentMember == childMember  //false, good
parentMember == parentExpMember  //true, good
childMember == childExpMember   //false, why?

推荐答案

取表达式的(第一个)参数的类型,然后说

Take the type of the expression's (first) parameter, and say

Expression<Func<C, string>> c = x => x.B; 
Type paramType = c.Parameters[0].Type;  // first parameter of expression
var d = paramType.GetMember((c.Body as MemberExpression).Member.Name)[0];

这篇关于Lambda 表达式未返回预期的 MemberInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆