c# - 是否有用于 C# 的 DataBinder.Eval 的快速版本?

标签 c# compilation eval expression

我想看看是否存在 ASP.NET 的 System.Web.UI.DataBinder.Eval() 的快速版本? 理想情况下,可以编译成我可以缓存并稍后调用的 Func,例如:

Func<object,string> expr = CompileDataBinder(typeof(Model), "model.PocoProperty.Name");
string propertyName = expr(model);

有谁知道这样的野兽是否存在?

附言我没有使用 ASP.NET,但希望它能在普通 C# 中工作

最佳答案

越看越想说:

Func<Model,string> expr = model => model.PocoProperty.Name;

如果您需要它基于字符串,Expression API 在那里非常公平。

class Program
{
    static void Main(string[] args)
    {
        Func<object, string> expr = CompileDataBinder(typeof(Model), "PocoProperty.Name");

        var model = new Model { PocoProperty = new ModelPoco { Name = "Foo" } };

        string propertyName = expr(model);
    }
    static Func<object, string> CompileDataBinder(Type type, string expr)
    {
        var param = Expression.Parameter(typeof(object));
        Expression body = Expression.Convert(param, type);
        var members = expr.Split('.');
        for (int i = 0; i < members.Length;i++ )
        {
            body = Expression.PropertyOrField(body, members[i]);
        }
        var method = typeof(Convert).GetMethod("ToString", BindingFlags.Static | BindingFlags.Public,
            null, new Type[] { body.Type }, null);
        if (method == null)
        {
            method = typeof(Convert).GetMethod("ToString", BindingFlags.Static | BindingFlags.Public,
                null, new Type[] { typeof(object)}, null);
            body = Expression.Call(method, Expression.Convert(body, typeof(object)));
        }
        else
        {
            body = Expression.Call(method, body);
        }

        return Expression.Lambda<Func<object, string>>(body, param).Compile();
    }
}

class Model
{
    public ModelPoco PocoProperty { get; set; }
}
class ModelPoco
{
    public string Name { get; set; }
}

关于c# - 是否有用于 C# 的 DataBinder.Eval 的快速版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5656256/

相关文章:

c++ - 未定义行为真的能帮助现代编译器优化生成的代码吗?

c++ - 如何编译使用 PlaySound 函数的 C++ 控制台应用程序?

javascript - 使用 try/catch 评估抛出错误

bash - 如何在 bash 中组合超时和 eval 命令

c# - 高度并行化的Levenshtein距离算法

c# - NoAutomaticTrigger 类型作业的连续 Azure WebJob 停止时的通知

c# - 使用终结器关闭EventHubClient

visual-studio-2012 - 是否可以在 Visual Studio 2012 中使用 VC++ 6 编译器?

javascript - 在不使用 eval 的情况下通过键路径从嵌套的 JSON 字典中获取值

c# - 响应重定向 '+'