越我看它,我就越想說:
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