Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//++ 合并两个pb结构++//
public static void mergeFromPb(object oldObj, object newObj, List<string> ignore_list = null){
if(oldObj.Equals(newObj))
return;
Type oldType = oldObj.GetType();
Type newType = newObj.GetType();
// if(oldType.Equals(newType) == false){
// return;
// }
PropertyInfo[] newInfos = newType.GetProperties();
PropertyInfo oldInfo = null;
FieldInfo fieldInfo = null;
PropertyInfo specifyInfo = null;
string proName = "";
bool hasProperty = false;
foreach(PropertyInfo newInfo in newInfos){
proName = newInfo.Name;
specifyInfo = newType.GetProperty(proName + "Specified");
if(specifyInfo != null){
hasProperty = (bool)specifyInfo.GetValue(newObj, null);
//Kof.Log(Kof.DEFAULT, "proName : " + proName + " Specified : " + hasProperty);
if(hasProperty == true){
fieldInfo = oldType.GetField(proName);
if(fieldInfo != null && fieldInfo.IsPublic){
fieldInfo.SetValue(oldObj, newInfo.GetValue(newObj, null));
}
oldInfo = oldType.GetProperty(proName);
if(oldInfo != null && oldInfo.CanWrite == true){
oldInfo.SetValue(oldObj, newInfo.GetValue(newObj, null), null);
}
}
}
else{
Type type = newInfo.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
//merge list
//Debug.Log(proName + "/" + newInfo.PropertyType);
PropertyInfo listCountInfo = type.GetProperty("Count");
if(listCountInfo != null){
object newListObj = newInfo.GetValue(newObj, null);
int itemCount = (int)listCountInfo.GetValue(newListObj, null);
//Kof.Log(Kof.DEFAULT, "itemCount : " + itemCount);
//++如果newList的长度<=0,则忽略;如果>0,则用newList的数据替换oldList的++//
if(itemCount > 0){
oldInfo = oldType.GetProperty(proName);
if(oldInfo != null){
object oldListObj = oldInfo.GetValue(oldObj, null);
//++先移除++//
MethodInfo remove = oldInfo.PropertyType.GetMethod("Clear");
remove.Invoke(oldListObj, new object[]{});
//++再添加++//
MethodInfo method = oldInfo.PropertyType.GetMethod("AddRange");
if(method != null){
method.Invoke(oldListObj, new object[]{newListObj});
}
}
else{
fieldInfo = oldType.GetField(proName);
if(fieldInfo != null){
fieldInfo.SetValue(oldObj, newInfo.GetValue(newObj, null));
}
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment