你如何获得一个C#属性名称与反思的字符串? [英] How do you get a C# property name as a string with reflection?
问题描述
可能重复:结果
的 C# - ?你如何获得一个变量的名称,因为它是在其声明中物理键入
我正在寻找一种方式来获得属性名称作为字符串这样我就可以有一个强类型的神奇的字符串。我需要做的是一样的东西MyClass.SomeProperty.GetName(),将返回SomeProperty。在C#这是可能的吗?
I'm looking for a way to get a property name as a string so I can have a "strongly-typed" magic string. What I need to do is something like MyClass.SomeProperty.GetName() that would return "SomeProperty". Is this possible in C#?
推荐答案
您可以使用表达式来实现这一点很容易。看到这个博客的一个样本。
You can use Expressions to achieve this quite easily. See this blog for a sample.
这使得它使您可以通过创建一个lambda表达式,并拉出名称。例如,实现INotifyPropertyChanged的可返工做这样的事情:
This makes it so you can create an expression via a lambda, and pull out the name. For example, implementing INotifyPropertyChanged can be reworked to do something like:
public int MyProperty {
get { return myProperty; }
set
{
myProperty = value;
RaisePropertyChanged( () => MyProperty );
}
}
为了映射你的等效,使用引用体现类,你会做这样的事情:
In order to map your equivalent, using the referenced "Reflect" class, you'd do something like:
string propertyName = Reflect.GetProperty(() => SomeProperty).Name;
维奥拉 - 属性的名称,而不串魔术
Viola - property names without magic strings.
这篇关于你如何获得一个C#属性名称与反思的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!