C# 如何从表达式树中获取属性名?

C# 如何从表达式树中获取属性名?,c#,linq,expression-trees,C#,Linq,Expression Trees,我的方法是 public Task<Product> GetProduct(int productId, params Expression<Func<Product, object>>[] properties) { var member = properties[0].Body as MemberExpression; var v = member.Member.Name; } 但这不是我想要的。 我很

我的方法是

    public Task<Product> GetProduct(int productId, params Expression<Func<Product, object>>[] properties)
    {

      var member = properties[0].Body as MemberExpression;
      var v = member.Member.Name;

    }
但这不是我想要的。 我很想得到所有的属性名和字符串。加入linq


我如何才能做到这一点?

使用
作为
操作符,然后过滤那些不是属性的。如果使用强制转换,它将抛出异常,但
as
将只返回null

var all =     
string.Join(", ", properties
.Select(x =>
    x.Body as MemberExpression))
.Where(x => x != null)
.Select(x =>
    x.Member.Name));

谢谢,它似乎足够接近了,但它只返回第一个参数名,这可能是因为您正在向该方法传递一个表达式。你需要传递尽可能多的表达式。有什么问题吗?如果您知道如何获取(选择)单个属性名,那么您应该能够使用简单的
select
——一个非常基本的LINQ运算符轻松获取所有属性名。
var all =     
string.Join(", ", properties
.Select(x =>
    x.Body as MemberExpression))
.Where(x => x != null)
.Select(x =>
    x.Member.Name));