解析表达式中的动态参数

时间:2018-06-29 18:55:44

标签: dynamic-expresso

了解我的情况的快速示例:

@model Final.Models.InputModel

@{
    ViewBag.Title = "Result";
    Layout = "~/Views/Shared/_Layout.cshtml";
}




    <br />
    <h4>Result</h4>
    <hr />


@using (Html.BeginForm("Result", "Find", FormMethod.Post))
{
    <p>The <b>@Model.SelectedText</b> files that contain <b>"@Model.Find"</b> are:  </p>
    <div>
        <table class="table table-bordered table-responsive table-hover">
            <tr>
                //HEADERS

            </tr>
            @foreach (var result in Model.Results)
            {
                // int i = 1;
                <tr>

                    <td>@result.SelectedText</td>
                    <td>@result.FileName</td>
                    <td>@result.Line</td>
                    <td>@result.LineCode</td>
                </tr>

            }
        </table>

        <div class="form-group">
            <div class="col-md-offset-2 ">

                <input type="submit" value="Export" name="export" class="btn btn-default">


            </div>
        </div>

    </div>
}







    <p>
        @Html.ActionLink("Back to List", "Index")
    </p>

换句话说,是否有办法将一些动态参数传递给Parse方法,然后获得一个接受此类参数的函子?

1 个答案:

答案 0 :(得分:1)

您可以直接使用Lambda方法返回的Parse类,而不必调用Compile函数:

var interpreter = new Interpreter()
string expression = "ctx.SomeProp";
Lambda parsedExpression = interpreter.Parse(expression, new Parameter("ctx", typeof(object)));
var token = JToken.Parse(s);
var result = parsedExpression.Invoke(token);

我没有完全测试您的代码,但是例如,我有这样的测试可以正常工作:

dynamic dyn = new ExpandoObject();
dyn.Foo = "bar";
var interpreter = new Interpreter()
    .SetVariable("dyn", (object)dyn);
Assert.AreEqual(dyn.Foo, interpreter.Eval("dyn.Foo"));

考虑到这仅适用于.NET 4.x,不支持.NET标准/核心动态。