我想获得的PropertyInfo特定属性。我可以使用:
I want to get the PropertyInfo for a specific property. I could use:
foreach(PropertyInfo p in typeof(MyObject).GetProperties()) { if ( p.Name == "MyProperty") { return p } }但是,必须有一种方法做类似
But there must be a way to do something similar to
typeof(MyProperty) as PropertyInfo是吗?还是我坚持做一个类型不安全的字符串比较?
Is there? Or am I stuck doing a type-unsafe string comparison?
干杯。
推荐答案您可以使用新的 nameof()操作符是在Visual Studio的C#6部分,可用2015年更多信息这里。
You can use the new nameof() operator that is part of C# 6 and available in Visual Studio 2015. More info here.
有关您的例子,你可以使用:
For your example you would use:
var result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));编译器将其转换 nameof(MyObject.MyProperty)字符串myProperty的,但你获得的能够重构属性名的好处,而无需记住修改字符串,因为Visual Studio中,ReSharper的等,知道如何重构 nameof()值。
The compiler will convert nameof(MyObject.MyProperty) to the string "MyProperty" but you gain the benefit of being able to refactor the property name without having to remember to change the string because Visual Studio, ReSharper, and the like know how to refactor nameof() values.
更多推荐
如何获取特定属性的PropertyInfo?
发布评论