Home  >  Article  >  Backend Development  >  What are the methods for generating GUID formats in C#?

What are the methods for generating GUID formats in C#?

零下一度
零下一度Original
2017-06-29 15:03:161932browse

1. GUID is a structure (struct) under the System namespace. An example is shown below.
(1) Create a GUID helper class (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) Use an example

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) Display the result

Default format: 4575c4b3-7997 -4f11-acd9-f107258e9adc
N format: a53a7186b583483aa4580519034e8095
D format: 5ae7f002-a989-4345-864b-3bcfbe09e1da
B format: {d9762660-8461-4c44- b714-8ffad6e1b79c}
P format (694ce704-0a7d-41d5-a25a-4eaedf7db50d)
Four formats for GUID generation

var uuid = Guid.NewGuid().ToString(); // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12
var uuidN = Guid.NewGuid().ToString("N"); // e0a953c3ee6040eaa9fae2b667060e09 
var uuidD = Guid.NewGuid().ToString("D"); // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12
var uuidB = Guid.NewGuid().ToString("B"); // {734fd453-a4f8-4c5d-9c98-3fe2d7079760}
var uuidP = Guid.NewGuid().ToString("P"); // (ade24d16-db0f-40af-8794-1e08e2040df3)
var uuidX = Guid.NewGuid().ToString("X"); // {0x3fa412e3,0x8356,0x428f,{0xaa,0x34,0xb7,0x40,0xda,0xaf,0x45,0x6f}}

The above is the detailed content of What are the methods for generating GUID formats in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn