【问题标题】:How to get the value of an expression如何获取表达式的值
【发布时间】:2011-08-10 06:38:17
【问题描述】:

我有这个使用 Linq 表达式的函数:

private Expression GetFieldValueExpression(ParameterExpression parameter, string fieldName)
{
  Expression properyIndexExpression = System.Linq.Expressions.Expression.Constant (fieldName, typeof(string));
  IndexExpression fieldValueExpression = System.Linq.Expressions.Expression.Property(parameter, "Item", new Expression[] { properyIndexExpression });
  return Expression.Property(fieldValueExpression, "Value");
}

Expression.Property(fieldValueExpression, "Value") 返回的值是字符串类型。

我不知道如何获得它。我知道我必须创建一个 lambda 并编译它,但我不知道如何。

感谢您的宝贵时间。

【问题讨论】:

  • 对不起,您无法获得财产价值是什么意思?你声称是字符串类型的?
  • 我需要获取这个方法返回的表达式的值。但我不知道怎么做。
  • 您能告诉我们,返回的方法是什么,或者您是否遇到任何错误/异常?
  • 此方法返回一个 System.Linq.Expressions.Expression 变量。没有错误。在下一步中,我需要执行这个表达式。

标签: c# .net linq lambda expression-trees


【解决方案1】:

也许你正在寻找这样的代码:

    public void EvaluateAnExpression()
    {
        //Make the parameter
        var parm = Expression.Parameter(typeof(TestClass),"parm");

        //Use your method to build the expression
        var exp = GetFieldValueExpression(parm, "testField");

        //Build a lambda for the expression
        var lambda = Expression.Lambda(exp, parm);

        //Compile the lamda and cast the result to a Func<>
        var compiled = (Func<TestClass, string>)lambda.Compile();

        //We'll make up some object to test on
        var obj = new TestClass();

        //Get the result (it will be TESTFIELD)
        var result = compiled(obj);
    }

该代码假定一些看起来像这样的测试类(基本上 indexer 属性只返回输入,但为大写 - 一个简单的示例,但适用于测试):

    public class TestClass
    {
        public InnerClass this[string indexParameter]
        {
            get
            {
                return new InnerClass { Value = indexParameter.ToUpper() };
            }
        }
    }

    public class InnerClass
    {
        public string Value { get; set; }
    }

【讨论】:

  • 非常感谢。这对我帮助很大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多