我创建了自己的序列化形式,它将提供的对象转换为字符串,然后我可以获得MD5哈希值。散列用于快速比较以查看特定属性是否已更改。但是我的代码非常慢,我想知道是否有人有更好的想法?
我需要仅担心标记有自定义[DatabaseMap]属性的对象中的属性。我并不太关心散列方法,而是关注对象在散列之前被序列化的方式。
有更好的方法吗?
public static string GetHash(this IBaseObject source)
{
if (source == null)
return string.Empty;
// step 1, calculate MD5 hash from input
var hasher = new ThreadLocal<MD5>(MD5.Create);
byte[] inputBytes = Encoding.UTF8.GetBytes(SerializeDataMembers(source, hasher)); // serialize the object
byte[] hash = hasher.Value.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < hash.Length; i++)
// {
// sb.Append(hash[i].ToString("X2"));
// }
// return sb.ToString();
return BitConverter.ToString(hash);
}
private static string SerializeDataMembers(IBaseObject source, MD5 hasher)
{
StringBuilder sb = new StringBuilder();
var properties = source.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
var attrs = Attribute.GetCustomAttributes(prop);
if (attrs.OfType<DatabaseMap>().Any())
{
if (prop.PropertyType == typeof (byte[]))
{
sb.Append(Convert.ToBase64String(hasher.ComputeHash((byte[])prop.GetValue(source))));
}
else
{
sb.Append(prop.GetValue(source));
}
}
}
return sb.ToString();
}
答案 0 :(得分:0)
Unit Of Work模式给了我一个想法。我完全删除了任何散列,并且对于我关心的特定属性属性,在他的setter中我比较是否有任何东西从旧值更改为新值,如果它有增量计数器。没有散列,速度非常快。
private void CompareChange<T>(T old, T newValue)
{
if (!EqualityComparer<T>.Default.Equals(old, newValue))
Interlocked.Increment(ref _ChangeCount);
}