简体   繁体   中英

How to get expression from expression-bodied property c#

I want to get the Expression of the Expression-bodied Property. I have no idea how to do that;/ Here is the simple code snippet:

class TestTest
{
    public int A { get; set; } = 5;

    public int AX5 => A * 5;
}
public class Program
{

    public static void Main()
    {
        var testObj = new TestTest();

        Expression<Func<TestTest, int>> expr = (t) => t.AX5;
    }

}

在此处输入图像描述

This code works, but AX5 is not marked as Expression, it is the simple Int32 property.

This is the result i want to get from the property: 在此处输入图像描述

The so called "Expression-Body" is just sugar to shorten function and property declarations. It does not have anything to do with the Expression<> type.

The 'expression-bodied' property in your class is equivalent to:

public int AX5 
{
    get { return A * 5; }
}

However, if you really wanted to capture this readonly property, you would have to retrieve the compiler generated get-method via reflection and then add an extra parameter to the Func<int> in order to pass the object-instance the property belongs to -> Func<TestTest, int> .

Here's an example:

class TestTest
{
    public int A { get; set; } = 5;

    public int AX5 => A * 5;
}

var f = typeof(TestTest).GetMethod("get_AX5")
                        .CreateDelegate(typeof(Func<TestTest, int>))
                        as Func<TestTest, int>;

Expression<Func<TestTest, int>> exp = instance => f(instance);

Note this is adding an additional function call to capture the new lambda-expression. Converting the get-method to an expression otherwise would get quite complicated.

This is not very useful though, usually you want to work the other way around and build Expression Trees to compile them to delegates later on.

Checkout the docs for Expression Trees for further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM