听起来你是用常规反射排序的,但是对于info,构建嵌套属性的表达式的代码与这个order-by代码非常相似.
请注意,要设置值,您需要GetSetMethod()
在属性上使用并调用它 - 在构造之后没有用于分配值的内置表达式(尽管4.0中支持).
(编辑)像这样:
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; class Foo { public Foo() { Bar = new Bar(); } public Bar Bar { get; private set; } } class Bar { public string Name {get;set;} } static class Program { static void Main() { Foo foo = new Foo(); var setValue = BuildSet("Bar.Name"); var getValue = BuildGet ("Bar.Name"); setValue(foo, "abc"); Console.WriteLine(getValue(foo)); } static Action BuildSet (string property) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); ParameterExpression valArg = Expression.Parameter(typeof(TValue), "val"); Expression expr = arg; foreach (string prop in props.Take(props.Length - 1)) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } // final property set... PropertyInfo finalProp = type.GetProperty(props.Last()); MethodInfo setter = finalProp.GetSetMethod(); expr = Expression.Call(expr, setter, valArg); return Expression.Lambda >(expr, arg, valArg).Compile(); } static Func BuildGet (string property) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach (string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } return Expression.Lambda >(expr, arg).Compile(); } }