我越看越想说:
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
方法而遇到了一些性能问题?如果是,您能否解释一下您的情况,展示您正在使用的代码,并评论一下在执行负载测试时所得到的结果,这些结果导致了您得出这个结论?如果不是,那么您为什么需要它呢? - Darin DimitrovEval
使用反射吗? - Gabe