ConcurrentDictionary的ToDictionary
如果Value是引用,那么在使用Value.Clear()的时候。会清空Value的所有元素,但是不会改变Value的引用
private static void Main() { try { var concurrentDictionary = new ConcurrentDictionary<string, List<int>>(); concurrentDictionary.TryAdd("chuck", new List<int>() {1, 2, 3}); concurrentDictionary.TryAdd("lihu", new List<int>() {4, 5, 6}); var dictionary = concurrentDictionary.ToDictionary(x => x.Key, x => x.Value); foreach (var list in concurrentDictionary.Values) { list.Clear(); } foreach (var name in dictionary.Keys) { Console.WriteLine(name); var list = dictionary[name]; foreach (var number in list) { Console.Write("\t{0}",number); } Console.WriteLine(); } } catch (Exception ex) { while (ex != null) { Console.WriteLine(ex.Message); ex = ex.InnerException; } } Console.ReadLine(); }
还需要测试下Value是List<Student>的情况
internal class Student { internal int Id { get; set; } internal string Name { get; set; } } internal class Program { private static void Main() { try { var concurrentDictionary = new ConcurrentDictionary<string, Student>(); concurrentDictionary.TryAdd("chuck", new Student() {Id = 1, Name = "chuck"}); concurrentDictionary.TryAdd("lihu", new Student() {Id = 2, Name = "lihu"}); var dictionary = concurrentDictionary.ToDictionary(x => x.Key, x => x.Value); foreach (var key in concurrentDictionary.Keys) { concurrentDictionary[key].Id = 0; concurrentDictionary[key].Name = "hello world"; } foreach (var name in dictionary.Keys) { Console.Write(name); Console.Write("\tid={0}\tname={1}", dictionary[name].Id, dictionary[name].Name); Console.WriteLine(); } } catch (Exception ex) { while (ex != null) { Console.WriteLine(ex.Message); ex = ex.InnerException; } } Console.ReadLine(); } }
Value是值类型的
private static void Main() { try { var concurrentDictionary = new ConcurrentDictionary<string, int>(); concurrentDictionary.TryAdd("chuck", 1); concurrentDictionary.TryAdd("lihu",4); var dictionary = concurrentDictionary.ToDictionary(x => x.Key, x => x.Value); foreach (var key in concurrentDictionary.Keys) { concurrentDictionary[key] = 0; } foreach (var name in dictionary.Keys) { Console.Write(name); Console.Write("\t{0}", dictionary[name]); Console.WriteLine(); } } catch (Exception ex) { while (ex != null) { Console.WriteLine(ex.Message); ex = ex.InnerException; } } Console.ReadLine(); }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2014-11-06 8.2.3多态性 第8章 面向对象编程简介