C#中GUID的生成以及格式

1、GUID是在System命名空間下的結構(struct)體,下面展示實例。
(1)創建一個GUID幫助類(GUIDHelper)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebDemo.guid
{
    public class GuIdHelper
    {
        /// <summary>
        /// GUID生成
        /// </summary>
        /// <param name="format">格式 可填寫N、D、B、P、X</param>
        /// <returns></returns>
        public static string GetNewGuId(string format="")
        {
            if (string.IsNullOrWhiteSpace(format))
                return Guid.NewGuid().ToString();
            else
                return Guid.NewGuid().ToString(format);
        }
    }
}

(2)使用實例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace WebDemo.guid
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            StringBuilder str = new StringBuilder();
            string[] array = {"","N","D","B","P","X" };
            foreach (var item in array)
            {
                if (string.IsNullOrWhiteSpace(item))
                    str.AppendFormat("默認格式:{0}", GuIdHelper.GetNewGuId());
                else
                    str.AppendFormat("<br />{0}格式:{1}", item, GuIdHelper.GetNewGuId(item));
            }
            Response.Write(str.ToString());
        }
    }
}

(3)顯示結果

默認格式:4575c4b3-7997-4f11-acd9-f107258e9adc
N格式:a53a7186b583483aa4580519034e8095
D格式:5ae7f002-a989-4345-864b-3bcfbe09e1da
B格式:{d9762660-8461-4c44-b714-8ffad6e1b79c}
P格式:(694ce704-0a7d-41d5-a25a-4eaedf7db50d)
X格式:{0x75198f26,0xac4e,0x42c8,{0x96,0x88,0xcc,0x91,0xe0,0xa6,0x9b,0x21}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章