在 C# 中,找出类是否具有属性的最佳方法是什么(使用反射)
我有一个类
public class Car
{
public string Name {get;set;}
public int Year {get;set;}
}
在单独的代码中,我有一个字段名称作为字符串(让使用“年份”)作为示例。
我想做这样的事情
if (Car.HasProperty("Year"))
,它可以确定汽车对象上是否有“年份”字段。这将返回 true。
if (Car.HasProperty("Model"))
会返回 false。
我看到代码循环遍历属性,但想看看是否有更简洁的方法来确定单个字段是否存在。
I have a class
public class Car
{
public string Name {get;set;}
public int Year {get;set;}
}
In seperate code, i have a field name as as string (let use "Year") as an example.
I want to do something like this
if (Car.HasProperty("Year"))
which would figure out if there is a Year field on the car object. This would return true.
if (Car.HasProperty("Model"))
would return false.
I see code to loop through properties but wanted to see if there was a more succinct way to determine if a single field exists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个扩展方法应该可以做到。
如果您想检查非实例属性、私有属性或其他选项,您可以调整该语句中的
BindingFlags
值。您的使用语法与您提供的不完全一样。反而:This extension method should do it.
If you wanted to check for non-instance properties, private properties, or other options, you can tweak the
BindingFlags
values in that statement. Your usage syntax wouldn't be exactly what you give. Instead:由于您似乎只查找
public
属性,Type.GetProperty()< /a> 可以完成这项工作:如果你想进一步抽象上面的代码,你可以在
Type 类
上编写一个扩展方法:然后像这样使用它:
如果你还想检查的存在非
public
属性,您必须调用 Type.GetProperties( ) 接受一个BindingFlags
参数,并像 David M 在他的答案中那样过滤结果。Since you seem to be looking only for
public
properties, Type.GetProperty() can do the job:If you want to further abstract the code above, you can write an extension method on the
Type class
:Then use it like this:
If you also want to check for the presence of non-
public
properties, you will have to call the override of Type.GetProperties() that takes aBindingFlags
argument, and filter the results as David M does in his answer.