简体   繁体   English

通过反射获取私有财产的名称,而无需使用字符串

[英]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. 前面的示例演示了如何将Util与公共属性一起使用,并且效果很好。 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. 但是,混淆后,该属性将不再称为MyPrivateProperty

I hope you get my point. 希望你明白我的意思。

Thanks for any help. 谢谢你的帮助。

Since the property is private you can not create a compile time expression targeting it. 由于该属性是私有的,因此无法创建针对它的编译时表达式。 What you could do is to decorate the property you are looking for with a custom attribute and search that via reflection. 您可以做的是使用自定义属性装饰要查找的属性,然后通过反射进行搜索。

Here is a quick example using a random CustomAttribute: 这是一个使用随机CustomAttribute的简单示例:

using System;
using System.Reflection;
using System.Linq;

public class C {
    [ObsoleteAttribute]
    private string P {get; set;}
}

public class C2
{
    String x = typeof(C)
        .GetProperties((BindingFlags)62)
        .Single(x => x.GetCustomAttribute<ObsoleteAttribute>() != null)
        .Name;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM