栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

C#日常开发随手记----解决一个集合引用另一个集合导致一起改变

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#日常开发随手记----解决一个集合引用另一个集合导致一起改变

深度拷贝(已封装为一个泛型通用方法复制即用):
/// 
/// 深度拷贝集合方法----解决一个集合引用另一个集合导致一起改变
/// 
/// 
/// 
/// 
/// 
public static List DeepCopyList(IList list1 , out List list2)
{
	MemoryStream ms = new MemoryStream();
	BinaryFormatter bf = new BinaryFormatter();
	bf.Serialize(ms, list1);
	ms.Position = 0;
	list2 = (List)bf.Deserialize(ms);
	return list2;
}

使用到的类(类需要标记可序列化特性):

[Serializable]
public class Student
{
	public int Id { get; set; }

	public int Age { get; set; }

}

测试方法:

static void Main(string[] args)
{
	var list1 = new List();
	Student stu1 = new Student();
	stu1.Id = 1;
	stu1.Age = 12;
	list1.Add(stu1);

	Student stu2 = new Student();
	stu2.Id = 2;
	stu2.Age = 21;
	list1.Add(stu2);

	Student stu3 = new Student();
	stu3.Id = 3;
	stu3.Age = 23;
	list1.Add(stu3);

	var list2 = new List();
	list2 = DeepCopyList(list1,out list2).Where(s => s.Id == 1).ToList();

	var ss = list2.Select(s => s.Age = 33).ToList();
}

结果:

转json
/// 
/// 转json方法----解决一个集合引用另一个集合导致一起改变
/// 
/// 
/// 
/// 
public static List Clone(this List list) where T : new()
{
	var str = JsonConvert.SerializeObject(list);
	return JsonConvert.DeserializeObject>(str);
}

使用到的类(类需要标记可序列化特性):

[Serializable]
public class Student
{
	public int Id { get; set; }

	public int Age { get; set; }

}

测试方法:

static void Main(string[] args)
{
	var list1 = new List();
	Student stu1 = new Student();
	stu1.Id = 1;
	stu1.Age = 12;
	list1.Add(stu1);

	Student stu2 = new Student();
	stu2.Id = 2;
	stu2.Age = 21;
	list1.Add(stu2);

	Student stu3 = new Student();
	stu3.Id = 3;
	stu3.Age = 23;
	list1.Add(stu3);

	var list2 = new List();
	list2 = Clone(list1).Where(s => s.Id == 1).ToList();

	var ss = list2.Select(s => s.Age = 33).ToList();
}

结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/820941.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号