Skip to content

Instantly share code, notes, and snippets.

@roowe
Forked from tiantian20007/gist:09179b4eb15e5a27b971
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roowe/d011a51f55079d6293da to your computer and use it in GitHub Desktop.
Save roowe/d011a51f55079d6293da to your computer and use it in GitHub Desktop.
//++ 合并两个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