c# foreach (property in object)... 有没有一种简单的方法可以做到这一点? [英] c# foreach (property in object)... Is there a simple way of doing this?

查看:27
本文介绍了c# foreach (property in object)... 有没有一种简单的方法可以做到这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个属性的类(如果有任何区别,所有属性都是字符串).
我还有一个列表,其中包含该类的许多不同实例.

I have a class containing several properties (all are strings if it makes any difference).
I also have a list, which contains many different instances of the class.

在为我的类创建一些单元测试时,我决定遍历列表中的每个对象,然后遍历该对象的每个属性...

While creating some unit tests for my classes I decided I wanted to loop through each object in the list and then loop through each property of that object...

我认为这样做很简单……

I thought doing this would be as simple as...

foreach (Object obj in theList)
{
     foreach (Property theProperties in obj)
     {
         do some stufff!!;
     }
}

但这没有用!:(我收到此错误...

But this didnt work! :( I get this error...

foreach 语句无法对类型为Application.Object"的变量进行操作,因为Application.Object"不包含GetEnumerator"的公共定义"

"foreach statement cannot operate on variables of type 'Application.Object' because 'Application.Object' does not contain a public definition for 'GetEnumerator'"

有没有人知道一种不用大量 if 和循环或不用太复杂的方法来做到这一点的方法?

Does anyone know of a way of doing this without tons of ifs and loops or without getting into anything too complex?

推荐答案

试试这个:

foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
   // do stuff here
}

另请注意,Type.GetProperties() 有一个重载,它接受一组绑定标志,因此您可以根据不同的标准(如可访问性级别)过滤掉属性,有关更多详细信息,请参阅 MSDN:Type.GetProperties 方法(BindingFlags) 最后但并非最不重要的是不要忘记添加system.反射"程序集参考.

Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.

例如解析所有公共属性:

For instance to resolve all public properties:

foreach (var propertyInfo in obj.GetType()
                                .GetProperties(
                                        BindingFlags.Public 
                                        | BindingFlags.Instance))
{
   // do stuff here
}

请告诉我这是否按预期工作.

Please let me know whether this works as expected.

这篇关于c# foreach (property in object)... 有没有一种简单的方法可以做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆