原文链接:https://blog.csdn.net/S2T11Enterprise/article/details/102364932

当我们需要将一个引用类型对象独立出来与原来的引用完全撇清关系时,可以使用这个方法。

/// <summary>
/// 克隆一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T Clone<T>(this T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}

if (ReferenceEquals(source, null))
{
return default(T);
}

var formatter = new BinaryFormatter();
var stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
使用方法,注意在调用之前,需要将 xXx 加上 Serializable 注解

var list = new List<xXx>();
var obj = list.clone();


相关文章:

  • 2022-03-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2021-06-21
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
  • 2021-05-17
  • 2021-06-01
  • 2021-06-02
相关资源
相似解决方案