如何让孩子从表达式中声明类型?

Tri*_*ion 13 .net c# linq lambda

我有一个Parent/Child类层次结构,其中Parent抽象地声明了一个字符串属性,而Child类实现了它:

abstract class Parent
{
   public abstract string Value { get; }
}

class Child : Parent
{
   public override string Value { get { return null; } }
}
Run Code Online (Sandbox Code Playgroud)

当我使用一个显式(或隐式)使用Child类的表达式时,我希望Expressions的MemberInfo的DeclaringType为'Child',而是它是Parent:

Child child = new Child();
Expression<Func<string>> expression = (() => child.Value);
MemberInfo memberInfo = expression.GetMemberInfo();
Assert.AreEqual(typeof(Child), memberInfo.DeclaringType); // FAILS!
Run Code Online (Sandbox Code Playgroud)

断言失败,因为DeclaringType是Parent.

在声明我的表达或消费它以揭示Child类型的实际用途时,我能做些什么吗?

注意:上面的GetMemberInfo()作为扩展方法(我甚至忘了我们写过这个!):

public static class TypeExtensions
{
    /// <summary>
    /// Gets the member info represented by an expression.
    /// </summary>
    /// <param name="expression">The member expression.</param>
    /// <returns>The member info represeted by the expression.</returns>
    public static MemberInfo GetMemberInfo(this Expression expression)
    {
        var lambda = (LambdaExpression)expression;

        MemberExpression memberExpression;
        if (lambda.Body is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)lambda.Body;
            memberExpression = (MemberExpression)unaryExpression.Operand;
        }
        else memberExpression = (MemberExpression)lambda.Body;

        return memberExpression.Member;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 11

否 - 这是C#编译器发出的内容的准确表示.在查找成员时,有效地忽略了覆盖 - 编译器只关心最初声明成员的类型.您可以通过编译代码然后查看IL来自行查看.这个方法:

static void Main()
{
    Child c = new Child();
    string x = c.Value;
}
Run Code Online (Sandbox Code Playgroud)

编译成这个IL:

IL_0000:  nop
IL_0001:  newobj     instance void Child::.ctor()
IL_0006:  stloc.0
IL_0007:  ldloc.0
IL_0008:  callvirt   instance string Parent::get_Value()
IL_000d:  stloc.1
IL_000e:  ret
Run Code Online (Sandbox Code Playgroud)

一点琐事:VB编译器的工作方式一样,所以这个方法:

Public Shared Sub Main(Args As String())
    Dim x As Child = New Child()
    Dim y As String = x.Value
End Sub
Run Code Online (Sandbox Code Playgroud)

编译为:

IL_0000:  newobj     instance void [lib]Child::.ctor()
IL_0005:  stloc.0
IL_0006:  ldloc.0
IL_0007:  callvirt   instance string [lib]Child::get_Value()
IL_000c:  stloc.1
IL_000d:  ret
Run Code Online (Sandbox Code Playgroud)


Tri*_*ion 5

我的解决方案,基于来自@JonSkeet 和@CodeInChaos 的信息,不是纯粹查看表达式中的 PropertyInfo,还要查看 MemberExpression 的 Member 组件的类型:

/// <summary>
/// Extracts the PropertyInfo for the propertybeing accessed in the given expression.
/// </summary>
/// <remarks>
/// If possible, the actual owning type of the property is used, rather than the declaring class (so if "x" in "() => x.Foo" is a subclass overriding "Foo", then x's PropertyInfo for "Foo" is returned rather than the declaring base class's PropertyInfo for "Foo").
/// </remarks>
/// <typeparam name="T"></typeparam>
/// <param name="propertyExpression"></param>
/// <returns></returns>
internal static PropertyInfo ExtractPropertyInfo<T>(Expression<Func<T>> propertyExpression)
{
    if (propertyExpression == null)
    {
        throw new ArgumentNullException("propertyExpression");
    }

    var memberExpression = propertyExpression.Body as MemberExpression;
    if (memberExpression == null)
    {
        throw new ArgumentException(string.Format("Expression not a MemberExpresssion: {0}", propertyExpression), "propertyExpression");
    }

    var property = memberExpression.Member as PropertyInfo;
    if (property == null)
    {
        throw new ArgumentException(string.Format("Expression not a Property: {0}", propertyExpression), "propertyExpression");
    }

    var getMethod = property.GetGetMethod(true);
    if (getMethod.IsStatic)
    {
        throw new ArgumentException(string.Format("Expression cannot be static: {0}", propertyExpression), "propertyExpression");
    }

    Type realType = memberExpression.Expression.Type;
    if(realType == null) throw new ArgumentException(string.Format("Expression has no DeclaringType: {0}", propertyExpression), "propertyExpression");

    return realType.GetProperty(property.Name);
}
Run Code Online (Sandbox Code Playgroud)