如何遍历类的属性? [英] How to loop through the properties of a Class?
问题描述
我发现这个问题很普遍,但是我没有找到想要的东西。也许是因为我想做其他事情。
I have found that this question is quite common, but i didn't found what i am looking for. Maybe 'cause i want to do something else.
因此,我目前正在为网络爬虫编写代码,需要比较列表中的对象。
我想做的事ist遍历列表,找到重复项,当发现重复项时将它们合并。
So i am currently coding for a webcrawler and need to compare objects in a list. What i want to do ist loop through the list, find duplicates, and when i found duplicates merge these.
合并时,我想:
-保留最新/最新对象的信息。
-如果最新对象的字段为空,则取旧对象字段的值
When merging i want to:
- keep the information of the latest/most up to date object.
- if a field of the latest object is empty, take the value of the old objects field
我认为循环遍历对象的属性两个对象将是最简单的。
I thought looping through the properties of the two objects would be the easiest.
我已经尝试了很多使用反射的方法,我所能实现的就是显示类的属性名称。我想要的是它们的值。
I've tried a lot of things using reflection, all i could achieve was to show the property names of a class. What i want though is their values.
如果可能的话,我会使用这样的循环:
If possible, i would use a loop like this:
foreach(property prop in myObject)
{
string value = myObject.prop;
//do something
}
有可能吗?还是我错过了什么?
Is that possible? Or am i missing something?
推荐答案
类似的东西:
object obj = new object();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (var p in properties)
{
var myVal = p.GetValue(obj);
}
请注意,您需要分配对象并将其传递给PropertyInfo。
Note you need to allocate the object and pass it into the PropertyInfo.
这篇关于如何遍历类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!