有人建议为此使用反射。我的方法效果很好,但是经过 800,000 次迭代后,我得出了一个明显的结论(大多数人已经得出),即反射并不能解决问题。
这是我的 Helper 类的一部分:
public static class Helper
{
public static string[] ignoredProperties =
{
"EntityState",
"EntityKey",
"Prop1",
"Prop2",
"Whatever",
};
/// <summary>
/// Check if properties of two objects are the same. Bypasses specified properties.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="first"></param>
/// <param name="other"></param>
/// <param name="ignoreProperties"></param>
/// <returns></returns>
public static bool PropertiesEquals<T>(this T first, T other, string[] ignoreProperties)
{
var propertyInfos = first.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
//Faster with custom method ? Nah...
//if (FindElementIndex(ignoreProperties, propertyInfo.Name) < 0)
//Probably faster if hardcoded.... Nah, not really either...
//if (propertyInfo.Name != "EntityKey" && propertyInfo.Name != "EntityState" && propertyInfo.Name != "Group_ID" && propertyInfo.Name != "Import_status")
if (Array.IndexOf(ignoreProperties, propertyInfo.Name) < 0)
if (!Equals(propertyInfo.GetValue(first, null), propertyInfo.GetValue(other, null)))
return false;
}
return true;
}
public static int FindElementIndex(string[] input, string value)
{
int arraySize = input.Length - 1;
Type valueType = value.GetType();
for (int x = 0; x <= arraySize; x++)
{
if (input[x] == value)
return x;
}
return -1;
}
问题是这些对象,根据类型,最多可以检查 50 个属性。所以我真的不能在那里做一堆if
s 。
有什么办法可以加快速度吗?
谢谢。