How can I get object instance from ()=>foo.Title expression

前端 未结 4 1377
感动是毒
感动是毒 2020-12-13 10:05

I have a simple class with a property

class Foo 
{ 
    string Title { get; set; } 
}

I am trying to simplify data binding by calling a fun

4条回答
  •  情书的邮戳
    2020-12-13 10:12

    Small LINQPad sample of what you want :

    void Foo(Expression> prop)
    {
        var propertyGetExpression = prop.Body as MemberExpression;
    
        // Display the property you are accessing, here "Height"
        propertyGetExpression.Member.Name.Dump();
    
        // "s" is replaced by a field access on a compiler-generated class from the closure
        var fieldOnClosureExpression = propertyGetExpression.Expression as MemberExpression;
    
        // Find the compiler-generated class
        var closureClassExpression = fieldOnClosureExpression.Expression as ConstantExpression;
        var closureClassInstance = closureClassExpression.Value;
    
        // Find the field value, in this case it's a reference to the "s" variable
        var closureFieldInfo = fieldOnClosureExpression.Member as FieldInfo;
        var closureFieldValue = closureFieldInfo.GetValue(closureClassInstance);
    
        closureFieldValue.Dump();
    
        // We know that the Expression is a property access so we get the PropertyInfo instance
        // And even access the value (yes compiling the expression would have been simpler :D)
        var propertyInfo = propertyGetExpression.Member as PropertyInfo;
        var propertyValue = propertyInfo.GetValue(closureFieldValue, null);
        propertyValue.Dump();
    }
    
    void Main()
    {
        string s = "Hello world";
        Foo(() => s.Length);
    }
    

提交回复
热议问题