使用反射来指定FUNC&LT的价值,产品,对象>属性 [英] Use reflection to assign value of Func<Product, object> property

查看:109
本文介绍了使用反射来指定FUNC&LT的价值,产品,对象>属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一类产品:

 公共类产品
{
    公共字符串名称{获取;组; }
    公共字符串制作{获得;组; }
    公共十进制价格{获得;组; } //(编辑) - 增加了非字符串
}
 

和我有另一个类的属性声明为:

  Func键<产品,对象> SortBy {获得;组; }
 

我可以SortBy使用设置:

  SortBy = P => p.Title;
 

不过,我将如何,使用反射,使同样的任务,如果我有一个字符串存储SortBy属性名称,如

 字符串=的SortField标题;

SortBy = / *使用一些的SortField反射* /;
 

解决方案

您需要使用的 EX pression树以在运行时创建一个新的方法:

  VAR P =前pression.Parameter(typeof运算(产品));
SortBy =前pression.Lambda< Func键<产品,对象>>(
    防爆pression.Property(P,的SortField)
    p
).Compile();
 

要与值类型的工作,你需要插入一个演员:

  VAR P =前pression.Parameter(typeof运算(产品));
SortBy =前pression.Lambda< Func键<产品,对象>>(
    防爆pression.TypeAs(出pression.Property(P,的SortField)的typeof(对象)),
    p
).Compile();
 

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*/;

解决方案

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

这篇关于使用反射来指定FUNC&LT的价值,产品,对象&gt;属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆