繁体   English   中英

表达式树linq获取参数值?

[英]expression trees linq get value of a parameter?

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;
    }
}

在上述代码中,我想获取属性标题的实际值,而不是属性名称的实际值,这可能吗?

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);
}

但是,您必须意识到这可能会很慢。 您应该衡量它在您的情况下的性能。

如果您不喜欢传递对象:

    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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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