有人建議使用反射來實現此目的。我使用的方法很好,但是超過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