本文介绍了Lambda表达式C#的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#中将属性名称转换为Lambda表达式?

How can I convert a property name to Lambda expression in C#?

像这样:string prop = "Name";到(p => p.Name)

public class Person{
    public string Name{ get; set; }
}

谢谢!

推荐答案

使用表达式树,您可以生成lambda表达式.

Using expression trees you can generate the lambda expression.

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;
}

对于Person,您可以这样称呼它:

for Person you can call it like:

var exp = GetPropertySelector<Person>("Name");//exp: x=>x.Name

这篇关于Lambda表达式C#的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:01