lundi 31 juillet 2017

Get name of private property via reflection without using a string

i want to get the name of a private property of a class. Reason is i want to set a property of that class that will be obfuscated later. What i have so far is the following:

public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
    var lambda = expression as LambdaExpression;
    MemberExpression memberExpression;
    var unaryExpression = lambda.Body as UnaryExpression;
    if (unaryExpression != null)
        memberExpression = unaryExpression.Operand as MemberExpression;
    else
        memberExpression = lambda.Body as MemberExpression;

    if (memberExpression == null)
        throw new ArgumentException("Expression must point to a Property");

    return memberExpression.Member.Name;
}

being called like this

private static readonly string DisplayNameProperty = ReflectionUtil.GetPropertyName<MyClass>(x => x.MyPublicProperty);

The previous example showed usage of the Util with a public property and it works perfectly. But on a private property it won't work because its private obviously.

Now what will work is:

typeof(MyClass).GetProperty("MyPrivateProperty", BindingFlags.NonPublic | BindingFlags.Instance)
                .SetValue(_myInstance, true, null);

But after being obfuscated the property will not be called MyPrivateProperty anymore.

I hope you get my point.

Thanks for any help.





Aucun commentaire:

Enregistrer un commentaire