1
1
Эх сурвалжийг харах

新增生成唯一短字符串方法

懒得勤快 7 жил өмнө
parent
commit
4b94e23e3f

+ 22 - 0
Masuit.Tools.Core/Extensions.cs

@@ -2,6 +2,8 @@
 using System.Collections.Generic;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;
+using Masuit.Tools.Security;
+using Masuit.Tools.Win32;
 using Newtonsoft.Json;
 
 namespace Masuit.Tools
@@ -1556,5 +1558,25 @@ namespace Masuit.Tools
         {
             return regex.Replace(input, replacement);
         }
+
+        /// <summary>
+        /// 生成唯一短字符串
+        /// </summary>
+        /// <param name="str"></param>
+        /// <param name="length">生成的字符串长度,越长冲突的概率越小,默认长度为10,最小长度为9,最大长度为32</param>
+        /// <returns></returns>
+        public static string CreateShortToken(this string str, int length = 10)
+        {
+            string temp = Guid.NewGuid().ToString("N").MDString();
+            if (length <= 32)
+            {
+                if (length < 9)
+                {
+                    length = 9;
+                }
+                temp = temp.Substring(new Random().StrictNext(32 - length), length);
+            }
+            return temp;
+        }
     }
 }

+ 22 - 0
Masuit.Tools/Extensions.cs

@@ -2,6 +2,8 @@
 using System.Collections.Generic;
 using System.Text.RegularExpressions;
 using System.Threading.Tasks;
+using Masuit.Tools.Security;
+using Masuit.Tools.Win32;
 using Newtonsoft.Json;
 
 namespace Masuit.Tools
@@ -1571,5 +1573,25 @@ namespace Masuit.Tools
         {
             return regex.Replace(input, replacement);
         }
+
+        /// <summary>
+        /// 生成唯一短字符串
+        /// </summary>
+        /// <param name="str"></param>
+        /// <param name="length">生成的字符串长度,越长冲突的概率越小,默认长度为10,最小长度为9,最大长度为32</param>
+        /// <returns></returns>
+        public static string CreateShortToken(this string str, int length = 10)
+        {
+            string temp = Guid.NewGuid().ToString("N").MDString();
+            if (length <= 32)
+            {
+                if (length < 9)
+                {
+                    length = 9;
+                }
+                temp = temp.Substring(new Random().StrictNext(32 - length), length);
+            }
+            return temp;
+        }
     }
 }

+ 9 - 5
Test/Program.cs

@@ -1,6 +1,6 @@
 using System;
 using System.Collections.Generic;
-using Masuit.Tools.Hardware;
+using Masuit.Tools;
 
 namespace Test
 {
@@ -51,10 +51,14 @@ namespace Test
 
             //MyClass mc = null;
             //MyClass2 mc2 = mc.Map<MyClass, MyClass2>();
-
-            string s = SystemInfo.GetLocalUsedIP();
-            Console.WriteLine(s);
-            Console.ReadKey();
+            Dictionary<string, object> dic = new Dictionary<string, object>();
+            for (int i = 0; i < 100000; i++)
+            {
+                string s = string.Empty.CreateShortToken(100);
+                Console.WriteLine(s);
+                dic.Add(s, s);
+            }
+            //Console.ReadKey();
         }
     }