Get the full name of a property

4

I am working on C #, using Linq Dynamic to do some sorting, so I was generated the need to obtain the names of the properties as string .

When the properties are simple, they do not generate any conflict, since I can use nameof() perfectly.

My problem is when I get the names of the daughters properties of objects.

I set an example to be interpreted

public class Padre
{
    public string Prop1 { get; set; }
    public Hijo H { get; set; }
}

public class Hijo
{
    public string Prop2 { get; set; }
}

When I want to access the name of Prop1 , I can do it perfectly as nameof(Prop1) .

The problem occurs when trying to get the name of Prop2 within an instance of Padre , for example

Padre p = new Padre();
string nombreProp2 = nameof(p.H.Prop2);

Where I want to get the string "H.Prop2" but I get only Prop2 , I currently get the value manually doing something like

string nombreProp2 = string.Format("{0}.{1}",nameof(p.H),nameof(p.H.Prop2))

Is there a more direct method of obtaining this data?

    
asked by Juan Salvador Portugal 22.11.2018 в 14:07
source

1 answer

3

I hope it serves you:

public static class ExpressionHelper
{
    public static string PathOf<T>(this T @object, Expression<Func<T, object>> expression)
    {
        return PathOf<T>(expression);
    }  

    static string PathOf<T>(Expression<Func<T, object>> expr)
    {
        MemberExpression memberExpression;

        switch (expr.Body.NodeType) {
            case ExpressionType.Convert:
            case ExpressionType.ConvertChecked:
                var unaryExpression = expr.Body as UnaryExpression;
                memberExpression = ((unaryExpression != null) ? unaryExpression.Operand : null) as MemberExpression;
                break;
            default:
                memberExpression = expr.Body as MemberExpression;
                break;
        }

        var path = string.Empty;
        while (memberExpression != null) {
            string propertyName = memberExpression.Member.Name;
            path += "." + propertyName;
            memberExpression = memberExpression.Expression as MemberExpression;
        }

        return path.Substring(path.IndexOf('.') + 1);
    }  
}

And you use it:

var p = new Padre();
var nombreProp2 = p.PathOf(x => x.H.Prop2);

And the result would be "H.Prop2".

    
answered by 22.11.2018 / 17:20
source