如何从类实例的属性中获取属性名称? [英] How to get a property name from the property of a class instance?

查看:37
本文介绍了如何从类实例的属性中获取属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要工作的代码:

This is the kind of code I'd like to make work:

string Name = GetPropName(myClass.SomeProperty); // returns "SomeProperty"

因为我可能会重命名我的类的属性,所以我不想忘记在我的代码中的某处更改它们的字符串名称,并且有很多地方我使用字符串名称作为属性,所以我想有这个方便的方法来为我获取属性的当前名称作为字符串.我该怎么做?

Because I might be renaming my class' properties, I wouldn't like to forget to change their string names somewhere in my code, and there are quite a few places I use string names for properties, so I'd like to have this handy method to get the current name of a property as string for me. How do I do this?

我所追求的是一个方法,它只返回它作为参数接收的属性的字符串名称.

What I'm after is a method that returns only the string name of the property it receives as a parameter.

我看到之前有人问过类似的问题,但没有答案可以很好地解释如何做我想做的事情.

推荐答案

调用方法并传入MyClass.MyProperty 的问题是属性的值发送给方法.您可以尝试使用反射从该值中获取属性名称,但这有两个问题:

The problem with calling the method and passing in MyClass.MyProperty is that the value of the property is sent to the method. You can try and use reflection to get the property name from that value, but there are two issues with that:

1 - 属性需要有一个值.

1 - The property needs to have a value.

2 - 如果相同类型的两个属性具有相同的值,则无法(至少据我所知)区分这两者.

2 - If two properties of the same type have the same values, there's no way (at least as far as I know) to differentiate the two.

您可以做的是使用 Expression 将属性传递给方法,获取该表达式的主体,最后获取成员(属性)名称:

What you could do though is use an Expression to pass the property into the method, get the body of that expression and finally the member (property) name:

 public static string GetPropertyName<T, P>(Expression<Func<T, P>> propertyDelegate)
 {
     var expression = (MemberExpression)propertyDelegate.Body;
     return expression.Member.Name;
 }

并使用它:

string myPropertyName = GetPropertyName((MyClass x) => x.SomeProperty);

这篇关于如何从类实例的属性中获取属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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