我遇到了一个我没想到的问题.一个例子可能比一段更好地说明我的问题:
更新:跳转到最后一个代码块,以获得更有说服力的代码示例.
public class A
{
public string B { get; set; }
}
public class C : A { }
Run Code Online (Sandbox Code Playgroud)
以下是方法中的一些代码:
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;
Run Code Online (Sandbox Code Playgroud)
以下是一些比较的结果:
a == b //false
a == d //false
b == d //true
Run Code Online (Sandbox Code Playgroud)
前两个有些出乎意料.我知道即使B不是虚拟的,C也可以用w new运算符定义一个具有相同名称的属性,但在这种情况下我没有.
第二个对我来说真是最让人惊讶的(也是我问题的核心).即使lambda的参数明确定义为C类,它仍然返回它,就像从基类访问属性一样.
我正在寻找的是一种从lambda表达式获取MemberInfo的方法,就好像我已经使用参数类型的反射来获取MemberInfo.我的项目本质上将MemberInfos存储在各种字典中,它需要具有可以通过提供lambda表达式来访问元素的功能.
重复的代码示例由Danny Chen提供
public class Base
{
public string Name { get; set; }
}
public class Derived : Base …Run Code Online (Sandbox Code Playgroud) 基本上,静态System.Linq.Expressions.Expression.Bind()方法中发生的一些内部检查在我的属性上显示"方法不是属性访问器",显然是属性.使用Reflector,我已经最小化了导致问题的代码量,而且我不能为我的生活找出为什么会发生这种情况.我唯一的猜测是它与属性不在类本身上这一事实有关,但我认为这应该仍然有效:
我试图用尽可能少的代码做一个小例子.下面的代码应该完整运行.
using System;
using System.Reflection;
public class Base
{
public virtual int Id { get; set; }
}
// As you can see, SubClass does not override the Id property of Base.
public class SubClass : Base { }
class Program
{
static void Main(string[] args)
{
// Getting the property directly from the type.
PropertyInfo propertyInfo = typeof(SubClass).GetProperty("Id");
MethodInfo setMethod = propertyInfo.GetSetMethod();
/* Code from here on out is from the System.Linq.Expressions.Bind() method (the one
that …Run Code Online (Sandbox Code Playgroud) 我已经构建了一个表达式树,它从类派生参数并调用它们来设置另一个类中的值.它适用于大多数类型,但在派生类型上失败.如果我有:
public class A
{
public string MyString {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
和
public class B : A
{
}
Run Code Online (Sandbox Code Playgroud)
如果我使用此表达式树代码(其中value是派生实例):
// Get the type of the object for caching and ExpressionTree purposes
var objectType = value.GetType();
// Define input parameter
var inputObject = Expression.Parameter( typeof( object ), "value" );
var properties = objectType.GetProperties( BindingFlags.Instance | BindingFlags.Public );
foreach (var property in properties)
{
Expression.Property( Expression.ConvertChecked( inputObject, property.DeclaringType ), property.GetGetMethod() )
}
Run Code Online (Sandbox Code Playgroud)
我会收到这个例外:
{System.ArgumentException: The method 'My.Namespace.A.get_MyString' is not …Run Code Online (Sandbox Code Playgroud)