C# helper Class

/// <summary>
/// 二进制序列化,带压缩
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string BinarySerialize(object obj)
{
string ret = string.Empty;
BinaryFormatter bf = new BinaryFormatter();

MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);

MemoryStream msZip = new MemoryStream();
GZipStream gZip = new GZipStream(msZip, CompressionMode.Compress);

byte[] aryByte = ms.ToArray();
gZip.Write(ms.ToArray(), 0, aryByte.Length);
aryByte = null;

ret = Convert.ToBase64String(msZip.ToArray());

gZip.Close();
msZip.Close();
ms.Close();

return ret;
}

/// <summary>
/// 二进制反序列化,带压缩
/// </summary>
/// <param name="binaryString"></param>
/// <returns></returns>
public static object BinaryDeserialize(string binaryString)
{
object obj = null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream msZip = new MemoryStream(Convert.FromBase64String(binaryString));

GZipStream gZip = new GZipStream(msZip, CompressionMode.Decompress);

MemoryStream ms = new MemoryStream();
int n;
byte[] bytes = new byte[2000];//一次最多读取2000字节
while ((n = gZip.Read(bytes, 0, bytes.Length)) != 0)
{
ms.Write(bytes, 0, n);
}

string all = Encoding.Default.GetString(ms.ToArray());

ms.Seek(0, SeekOrigin.Begin);
obj = bf.Deserialize(ms);

gZip.Close();
msZip.Close();
ms.Close();
bytes = null;

return obj;
}
/// <summary>
/// dataTable transfer DTO
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static T GetEntity<T>(DataTable table) where T : new()
{
T entity = new T();
foreach (DataRow row in table.Rows)
{
foreach (var item in entity.GetType().GetProperties())
{
if (row.Table.Columns.Contains(item.Name))
{
if (DBNull.Value != row[item.Name])
{
item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
}

}
}
}

return entity;
}

/// <summary>
/// dataTable transfer DTOList
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static IList<T> GetEntities<T>(DataTable table) where T : new()
{
IList<T> entities = new List<T>();
foreach (DataRow row in table.Rows)
{
T entity = new T();
foreach (var item in entity.GetType().GetProperties())
{
item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
}
entities.Add(entity);
}
return entities;
}

转载于:https://www.cnblogs.com/watchfluture/p/8953019.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值