C#中Model复制与对比源码,要复制的Model需要在定义Model的类前加上[Serializable]序列化。
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
namespace HdhCmsModel
{
/// <summary>
/// 对比两个实体类 是否一致。ContrastModel
/// </summary>
public class HdhModelDo
{
/// <summary>
/// 深度复制
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T DeepCopy<T>(T obj)
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, obj);
memoryStream.Seek(0, SeekOrigin.Begin);
var t = (T)binaryFormatter.Deserialize(memoryStream);
return t;
}
/// <summary>
/// 对比是否有修改
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="s"></param>
/// <returns></returns>
public static bool ForCheck<T>(T t,T s)
{
Type type = typeof(T);
PropertyInfo[] ps = type.GetProperties();
int rst = 0;
foreach (PropertyInfo pp in ps)
{
var val_t = pp.GetValue(t);
var val_s = pp.GetValue(s);
if (val_s == null)
{
val_s="";
}
if (val_t == null)
{
val_t = "";
}
if (val_t.GetType() == typeof(String))//深度复制 字符串差异-> 无转空、大写转小写、首字母加空格
{
if (val_s == null) val_s = "";
if (val_t.ToString().ToUpper() == val_s.ToString().ToUpper())
{
continue;
}
if (val_t.ToString().Trim() == val_s.ToString().Trim())
{
continue;
}
}
if (!Equals(val_t, val_s))
rst++;
}
return rst == 0;//没改
}
}
}
Model源码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HdhCmsModel
{
[Serializable]
public partial class hdhcmsclass
{
private int _id = 0; //| 自动编号
private string _hdhcmsshortcode; //简称编码
private string _hdhcmschinesename; //| 中文名名
private string _hdhcmsenglishname; //| 英文名名
private int _isdelete = 0; //| 删除标记
public int id { get { return _id; } set { _id = value; } }
public string hdhcmsshortcode { get { return _hdhcmsshortcode; } set { _hdhcmsshortcode = value; } }
public string hdhcmschinesename { get { return _hdhcmschinesename; }set { _hdhcmschinesename = value; } }
public string hdhcmsenglishname { get { return _hdhcmsenglishname; } set { _hdhcmsenglishname = value; } }
public int isdelete { get { return _isdelete;} set { _isdelete = value; } }
}
}
调用 :
productbigclass m =HdhModelDo.DeepCopy(_productbigclass);//深度复制
FormTheNewValueToModel(ref m);//获取页面新值处理
if (CtrstM.ForCheck(m, _productbigclass)) MessageBox.Show("值未做修改");
查看更多关于C#中复制Model修改后再对两个MODEL进行对比的源码的详细内容...