在實際的設計當中,我們往往在許多地方需要用到不規則的唯一值(標識),比如在購物車ID、數據標識、消息隊列的標識等等。C#為我們提供了一個Guid,可以輕松的獲取到不規則的唯一值(標識),具體的方法如下:
using System;
...
private static void CreatGuid()
{
Response.Write("GUID:" + Guid.NewGuid().ToString());
}
...
下面來寫一個生成GUID的函數:
private string getGUID()
{
System.Guid guid = new Guid();
guid = Guid.NewGuid();
string str = guid.ToString();
return str;
}
隨機生成如下字符串:
e92b8e30-a6e5-41f6-a6b9-188230a23dd2
格式說明:
System.Guid.NewGuid().ToString(format)
格式說明符
返回值的格式
N 32位:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
如:e92b8e30a6e541f6a6b9188230a23dd2
D 由連字符分隔的32位數字:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
如:e92b8e30-a6e5-41f6-a6b9-188230a23dd2
B 括在大括號中、由連字符分隔的32位數字:
{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
如:{e92b8e30-a6e5-41f6-a6b9-188230a23dd2}
P 括在圓括號中、由連字符分隔的32位數字:
(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
如:(e92b8e30-a6e5-41f6-a6b9-188230a23dd2)
聲明:轉載本文請注明來源于西部e網(weste.net)。