简体   繁体   English

反射:获取静态属性名称

[英]Reflection : get static property name

I need to get the property name of a static property dynamically called as a parameter. 我需要获取动态称为参数的静态属性的属性名称。 Here is my Portable Class Library code: 这是我的可移植类库代码:

public partial class Test
    {
        public Test()
        {
            string staticPropName = Test.GetPropName(Test.Row); // result must be "Row" without additional string
            System.Diagnostics.Debug.WriteLine("propName=" + staticPropName);
        }

        public static int Row { get; set; }

        public static string GetPropName(object Property)
        {
            return "Row"; // using reflection
        }
    }

I don't know the name of the property and I don't want to define it with an additional string. 我不知道属性的名称,也不想使用其他字符串来定义它。

You can't do that - when function is called it gets value of the property and have no idea where this value come from. 您无法做到这一点-调用函数时,它获取属性的值,却不知道该值从何而来。 Your sample is equivalent of 您的样本等于

     string staticPropName = Test.GetPropName(42); 

which nobody would expect to return name. 没有人会期望返回名字。

You can try to require Expression as argument so you can actually inspect what method get called with like following staring point ( https://stackoverflow.com/questions/1011109/how-do-you-get-the-name-of-the-property ): 您可以尝试将Expression作为参数,这样您就可以实际检查调用哪种方法,例如跟随凝视点( https://stackoverflow.com/questions/1011109/how-do-you-get-the-name-of-the -属性 ):

public static string GetPropName<TResult>(Expression<Func<TResult>> expression)
{ 
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

string staticPropName = Test.GetPropName(()=> Test.Prop); 

Note that you need checks to make sure expression is just one you expect and not something like () => Test + 42 or more complex one and report nice error. 请注意,您需要进行检查以确保表达式只是您期望的表达式,而不是() => Test + 42或更复杂的表达式,并且报告不错的错误。

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

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