越我看它,我就越想说:
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; }
}
您目前遇到了一些性能问题,由于经典'Eval'方法?如果是的话,你能否解释一下你的情况,展示你正在使用的代码,评论你在执行负载测试时得到的结果,从而得出这个结论?如果不是,你为什么需要这个? – 2011-04-13 22:11:23
因为我真的关心性能,不想在编译的模板中包含低效的执行路径。 – mythz 2011-04-13 22:13:46
@mythz,'Eval'并不低效。许多繁忙的交通网站正在使用它。 – 2011-04-13 22:14:21