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

↘锁芯ラ 提交于 2019-12-07 16:43:48

问题


If I have a class Product:

public class Product
{
    public string Title { get; set; }
    public string Make { get; set; }
    public Decimal Price { get; set; } //(Edit) - Added non-string
}

And I have a property in another class declared as:

Func<Product, object> SortBy { get; set; }

I can set SortBy using:

SortBy = p => p.Title;

But how would I, using reflection, make the same assignment if I had the property name for SortBy stored as a string e.g.

string sortField = "Title";

SortBy = /*Some reflection using sortField*/;

回答1:


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();



回答2:


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>



回答3:


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



来源:https://stackoverflow.com/questions/9756407/use-reflection-to-assign-value-of-funcproduct-object-property

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