expression trees linq get value of a parameter?

2019-06-11 10:58发布

问题:

AddOptional<tblObject>(x =>x.Title, objectToSend.SupplementaryData);

private static void AddOptional<TType>(Expression<Func<TType,string>> expr, Dictionary<string, string> dictionary)
{
    string propertyName;
    string propertyValue;

    Expression expression = (Expression)expr;
    while (expression.NodeType == ExpressionType.Lambda)
    {
        expression = ((LambdaExpression)expression).Body;
    }
}

In Above code i would like to get actual value of property title, not ony propert name , is it possible ?

回答1:

private static void Main(string[] args)
{
    CompileAndGetValue<tblObject>(x => x.Title, new tblObject() { Title =  "test" });
}

private static void CompileAndGetValue<TType>(
    Expression<Func<TType, string>> expr,
    TType obj)
{
    // you can still get name here

    Func<TType, string> func = expr.Compile();
    string propretyValue = func(obj);
    Console.WriteLine(propretyValue);
}

However, you must be aware that this can be quite slow. You should measure how it performs in your case.

If you don't like to pass your object:

    private static void Main(string[] args)
    {
        var yourObject = new tblObject {Title = "test"};
        CompileAndGetValue(() => yourObject.Title);
    }


    private static void CompileAndGetValue(
        Expression<Func<string>> expr)
    {
        // you can still get name here

        var func = expr.Compile();
        string propretyValue = func();
        Console.WriteLine(propretyValue);
    }