Rob*_*Rob 3 .net c# reflection func
如果我有一个产品类:
public class Product
{
public string Title { get; set; }
public string Make { get; set; }
public Decimal Price { get; set; } //(Edit) - Added non-string
}
Run Code Online (Sandbox Code Playgroud)
我在另一个类中有一个属性声明为:
Func<Product, object> SortBy { get; set; }
Run Code Online (Sandbox Code Playgroud)
我可以使用以下方法设置SortBy:
SortBy = p => p.Title;
Run Code Online (Sandbox Code Playgroud)
但是,如果我将SortBy的属性名称存储为字符串,我将如何使用反射进行相同的赋值
string sortField = "Title";
SortBy = /*Some reflection using sortField*/;
Run Code Online (Sandbox Code Playgroud)
您需要使用表达式树在运行时创建新方法:
var p = Expression.Parameter(typeof(Product));
SortBy = Expression.Lambda<Func<Product, object>>(
Expression.Property(p, sortField),
p
).Compile();
Run Code Online (Sandbox Code Playgroud)
要使用值类型,您需要插入一个强制转换:
var p = Expression.Parameter(typeof(Product));
SortBy = Expression.Lambda<Func<Product, object>>(
Expression.TypeAs(Expression.Property(p, sortField), typeof(object)),
p
).Compile();
Run Code Online (Sandbox Code Playgroud)