【发布时间】:2018-06-29 04:44:35
【问题描述】:
我正在尝试编写一个扩展方法,根据对象的字段比较对象。
我有这个:
public static class MyExtensions
{
public static bool FieldsEquals(this object o, object other)
{
if (ReferenceEquals(o, other))
return true;
if (o == null || other == null || o.GetType() != other.GetType())
return false;
foreach (var f in o.GetType().GetFields())
{
// is this a correct test ???
bool isEnumerable = f.FieldType != typeof(string) &&
typeof(IEnumerable).IsAssignableFrom(f.FieldType);
if (!isEnumerable)
{
if (!f.GetValue(o).Equals(f.GetValue(other)))
return false;
}
else
{
// convert both to IEnumerable and check if equal
}
}
return true;
}
}
我正在努力解决该领域是一个集合的情况;我需要检测这种情况,然后检查集合是否相同(相同数量的元素和f.GetValue(o)[i] == f.GetValue(other)[i]。
有什么帮助吗?
【问题讨论】: