C#:在链从lambda表达式获得属性的名称 [英] C#: Getting Names of properties in a chain from lambda expression

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

问题描述

我正在开发一个使用lambda表达式来指定属性的API。我使用这个著名的一段类似的代码这一项(这是简化和不完整的,只是为了清楚我说的):

I'm developing a API that uses lambda expressions to specify properties. I'm using this famous piece of code similar to this one (this is simplified and incomplete, just to make clear what I'm talking about):

public void Foo<T, P>(Expression<Func<T, P>> action)
{
    var expression = (MemberExpression)action.Body;
    string propertyName = expression.Member.Name;
    // ...
}

要这样调用:

Foo((String x) => x.Length);

现在我想通过链接的属性名称,像这样指定属性路径:

Now I would like to specify a property path by chaining property names, like this:

Foo((MyClass x) => x.Name.Length);



富应该能够路径分成其属性名(名称长度)。有没有办法用合理的努力来做到这一点?

Foo should be able to split the path into its property names ("Name" and "Length"). Is there a way to do this with reasonable effort?


有一个<一个HREF =htt​​p://stackoverflow.com/questions/995142/combining-lambda-expressions-to-property-paths>不知何故容貌相似的问题,但我认为他们正试图lambda表达式有结合起来。

There is a somehow similar looking question, but I think they are trying to combine lambda expressions there.

另一个问题也是处理嵌套属性的名字,但我真的不明白他们在说什么。

Another question also is dealing with nested property names, but I don't really understand what they are talking about.

推荐答案

像这样

public void Foo<T, P>(Expression<Func<T, P>> expr)
{
    MemberExpression me;
    switch (expr.Body.NodeType)
    {
        case ExpressionType.Convert:
        case ExpressionType.ConvertChecked:
            var ue = expr.Body as UnaryExpression;
            me = ((ue != null) ? ue.Operand : null) as MemberExpression;
            break;
        default:
            me = expr.Body as MemberExpression;
            break;
    }

    while (me != null)
    {
        string propertyName = me.Member.Name;
        Type propertyType = me.Type;

        Console.WriteLine(propertyName + ": " + propertyType);

        me = me.Expression as MemberExpression;
    }
}

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

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