c# – 将Guid与字符串进行比较
发布时间:2020-12-15 18:26:33 所属栏目:百科 来源:网络整理
导读:我很惊讶我无法在Google或SO上找到答案,但考虑到案例,将字符串与Guid进行比较的最佳方法是什么,如果合适,还有 const string sid = "XXXXX-...."; // This comes from a third party libraryGuid gid = Guid.NewGuid(); // This comes from the dbif (gid.ToS
我很惊讶我无法在Google或SO上找到答案,但考虑到案例,将字符串与Guid进行比较的最佳方法是什么,如果合适,还有
const string sid = "XXXXX-...."; // This comes from a third party library Guid gid = Guid.NewGuid(); // This comes from the db if (gid.ToString().ToLower() == sid.ToLower()) if (gid == new Guid(sid)) // Something else? 更新: 解决方法
不要将Guids比作字符串,也不要从字符串创建新的Guid,只是为了将它与现有的Guid进行比较.
除了性能之外,没有一种标准格式可以将Guid表示为字符串,因此您冒着比较不兼容格式的风险,您必须通过配置String.Compare来执行此操作或将每个格式转换为小写,从而忽略大小写. . 一种更惯用且更高效的方法是从常量字符串值创建静态的只读Guid,并使用本机Guid相等性创建所有比较: const string sid = "3f72497b-188f-4d3a-92a1-c7432cfae62a"; static readonly Guid guid = new Guid(sid); void Main() { Guid gid = Guid.NewGuid(); // As an example,say this comes from the db Measure(() => (gid.ToString().ToLower() == sid.ToLower())); // result: 563 ms Measure(() => (gid == new Guid(sid))); // result: 629 ms Measure(() => (gid == guid)); // result: 10 ms } // Define other methods and classes here public void Measure<T>(Func<T> func) { Stopwatch sw = new Stopwatch(); sw.Start(); for(int i = 1;i<1000000;i++) { T result = func(); } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } 因此,字符串比较和从常量值创建新Guid比将Guid与从常量值创建的静态只读Guid相比要贵50-60倍. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |