【问题标题】:Any way to generate GUID like the following?有什么方法可以生成如下所示的 GUID?
【发布时间】:2011-02-23 06:27:30
【问题描述】:

如何生成类似于以下内容的 GUID:00000000-0000-0000-0000-B7B9B3A4A0DE

除了最后一部分,应该都是零。

【问题讨论】:

  • 看起来您已经这样做了。你能解释一下你想在这里做什么吗?这有一种糟糕的代码味道。

标签: c# guid


【解决方案1】:

你的意思不是很清楚。例如,这有效:

Guid guid = Guid.Parse("00000000-0000-0000-0000-B7B9B3A4A0DE");

因此,您可以毫无问题地将文本转换为 Guid。如果您想生成这样的 Guid,您总是可以生成 6 个随机字节(例如使用 RandomNumberGenerator)并将适当的字节数组传递给 Guid(byte[])。例如:

using System;
using System.Security.Cryptography;

class Test
{
    static void Main()
    {
        var rng = RandomNumberGenerator.Create();
        byte[] randomBytes = new byte[6];
        rng.GetBytes(randomBytes);

        byte[] guidBytes = new byte[16];
        Buffer.BlockCopy(randomBytes, 0, guidBytes, 10, 6);

        Guid guid = new Guid(guidBytes);
        Console.WriteLine(guid);
    }
}

【讨论】:

  • 你的答案可能比我的效率高得多,因为它不涉及字符串操作。
【解决方案2】:

我的建议是使用Guid.NewGuid() 生成标准Guid,将其转换为字符串,然后使用new Guid('0000 etc.') 将其转回Guid,例如,

var guidString = Guid.NewGuid().ToString();
/* manipulate guidString to zero out all but the last parts */
var guid = new Guid(guidString);

【讨论】:

    【解决方案3】:
    new Guid("00000000-0000-0000-0000-" + Guid.NewGuid().ToString().Substring(24, 12))
    

    【讨论】:

      猜你喜欢
      • 2011-02-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多