有人建议使用反射来实现此目的。我使用的方法很好,但是超过80万次迭代,我得出了明显的结论(大多数已经出现),反射并没有削减它。比较两个物体属性的最快方法
这里是我的助手类的一部分:
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级性能检查。呃...所以我真的不能做一堆如果在那里。
有什么办法可以加快这一点吗?
谢谢。
解决方法:使用Equals方法并为每个类重写它以实现该属性比较(不反射)。 – Keith