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

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

问题描述

这是我想要做的代码方面的工作:

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.

什么你可以做虽然是使用表达式来的财产传递给方法,得到的身体表达最后的成员(属性)名称:

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天全站免登陆