Use reflection to assign value of Func<Product, object> property

爱⌒轻易说出口 提交于 2019-12-05 19:57:09

You need to use expression trees to create a new method at runtime:

var p = Expression.Parameter(typeof(Product));
SortBy = Expression.Lambda<Func<Product, object>>(
    Expression.Property(p, sortField),
    p
).Compile();

To work with value types, you'll need to insert a cast:

var p = Expression.Parameter(typeof(Product));
SortBy = Expression.Lambda<Func<Product, object>>( 
    Expression.TypeAs(Expression.Property(p, sortField), typeof(object)), 
    p
).Compile();

To make it work with decimal and other value types, you can use generics:

static void SetSortBy<T>(string sortField) {
    var m = typeof(Product).GetProperty(sortField).GetGetMethod();
    var d = Delegate.CreateDelegate(typeof(Func<Product, T>), m) 
            as Func<Product, T>;
    SortBy = product => d(product);
}

...

SetSortBy<decimal>("Price");
SetSortBy<object>("Title"); // or <string>

The answer is effectively the same as this other SO question/answer on INotifyPropertyChanged by Phil.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!