如何在C#中将属性名称转换为Lambda表达式?
像这样: string prop = "Name";到(p => p.Name)
public class Person{
public string Name{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Tah*_*ooy 19
使用表达式树可以生成lambda表达式.
using System.Linq.Expressions;
public static Expression<Func<T, object>> GetPropertySelector<T>(string propertyName)
{
var arg = Expression.Parameter(typeof(T), "x");
var property = Expression.Property(arg, propertyName);
//return the property as object
var conv = Expression.Convert(property, typeof(object));
var exp = Expression.Lambda<Func<T, object>>(conv, new ParameterExpression[] { arg });
return exp;
}
Run Code Online (Sandbox Code Playgroud)
因为Person你可以称之为:
var exp = GetPropertySelector<Person>("Name");//exp: x=>x.Name
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4411 次 |
| 最近记录: |