如何获取特定属性的PropertyInfo?

编程入门 行业动态 更新时间:2024-10-28 06:26:36
本文介绍了如何获取特定属性的PropertyInfo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想获得的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?

本文发布于:2023-11-03 07:00:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   PropertyInfo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!