猿问
循环遍历C#中的对象属性
我有两个相同类型的对象,我想循环遍历每个对象的公共属性,并提醒用户哪些属性不匹配。
是否可以在不知道对象包含哪些属性的情况下执行此操作?
Smart猫小萌
浏览 1318
回答 3
3回答
慕容708150
是的,使用反射 - 假设每种属性类型都Equals适当地实现。另一种方法是ReflectiveEquals递归使用除了一些已知类型之外的所有类型,但这很棘手。public bool ReflectiveEquals(object first, object second){ if (first == null && second == null) { return true; } if (first == null || second == null) { return false; } Type firstType = first.GetType(); if (second.GetType() != firstType) { return false; // Or throw an exception } // This will only use public properties. Is that enough? foreach (PropertyInfo propertyInfo in firstType.GetProperties()) { if (propertyInfo.CanRead) { object firstValue = propertyInfo.GetValue(first, null); object secondValue = propertyInfo.GetValue(second, null); if (!object.Equals(firstValue, secondValue)) { return false; } } } return true;}
0
0
0
随时随地看视频
慕课网APP
相关分类
C#
typedef入门问题
1 回答
.NET
.net 中 字符串含有超链接,如何给超链接自动加上a标签?
1 回答
请问.net 中用jquery传值安全吗?
2 回答
我要回答