场景:在窗口关闭的时候(用户点击叉叉的时候),需要比较用户在当前页面是否有修改,如果有需要提示是否要保存,如果没有才能关闭页面。
两种解决方案:
已知集合:LstConfig(当前的集合) _localLstConfig(在打开页面随即缓存的初始数据集合)
第一种:集合直接比较
public bool JudgeIsChanged() { if(LstConfig is {Count :var newConfigCount} && _localLstConfig is {Count:var oldConfigCount}) { if(newConfigCount != oldConfigCount){ return true; } else //数量相同比较内容 { var srGroup = LstConfig.Where(x=>!_localLstConfig.Any(o=>x.Name==o.Name && x.IsEnabled==o.IsEnabled)).ToList(); if(srGroup is {Count: >0 }) return true; else return false; } } else return true; }
第二种:集合转成字符文件保存,比较字符文件判断差异
/// <summary> /// 缓存目录 /// </summary> private string _cachePath { get { var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetFileName(Assembly.GetEntryAssembly()?.GetName().Name), @"Cache\ConfigJson"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } } /// <summary> /// 记录配置信息 /// </summary> private void RecordConfig() { if (StorageConfig != null) { var filePath = Path.Combine(_cachePath, "StorageConfig"); if (File.Exists(filePath)) File.Delete(filePath); File.Create(filePath, Encoding.UTF8.GetBytes(StorageConfig.ToJson())); } } /// <summary> /// 读文件 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public string ReadFile(string filePath) { var content = string.Empty; try { if (File.Exists(filePath)) { using var fs = new FileStream(filePath, FileMode.Open); using var sr = new StreamReader(fs); content = sr.ReadToEnd(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return content; } /// <summary> /// 判断是否更新 /// </summary> /// <returns></returns> public bool IsUpdate() { if (StorageConfig != null) { var filePath = Path.Combine(_cachePath, "StorageConfig"); var oldJson = ReadFile(filePath); var newJson = StorageConfig.ToJson(); return oldJson != newJson; } return false; }
标签:return,filePath,差异,StorageConfig,var,如何,集合,Path From: https://www.cnblogs.com/moon-stars/p/18098629