是否有这样做的一个简单的方法

是否有这样做的一个简单的方法

本文介绍了C#的foreach(对象属性)...是否有这样做的一个简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含几个属性(都是字符串,如果这有什么差别)的一类。结果
我也有一个列表,其中包含类的许多不同的实例。

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'"

有谁知道这样做没有吨IFS和循环或的一种方式,而不进入任何事情太复杂?

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了解详情:最后但并非最不重要不要忘了添加的System.Reflection集引用。

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(对象属性)...是否有这样做的一个简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:40