如何在C#中生成UUID

186

我正在通过程序创建一个 .idl 文件。如何通过程序创建接口和方法的 UUID。

我能否通过程序生成 UUID?


31
你的意思是 Guid.NewGuid() 吗? - SLaks
5个回答

316

43
你也可以使用这段代码生成一个字符串类型的 UUID:UUID.randomUUID().toString()。 - Justin
15
GUID和UUID是一样的吗? - Uma Shankar Subramani
24
GUID是全球唯一标识符的缩写,UUID是通用唯一标识符的缩写。这两个词汇表示同一个概念。 - Tudor
7
如果您想与某些无法理解小写UUID的MS Build工具兼容,那么您可能希望执行System.Guid.NewGuid().ToString("B").ToUpper()。例如,vdproj设置项目中的UUID是大写的,如果您提供小写的UUID,则会引发异常。 - Mark Lakata
6
不同的概念,表现形式相同但方案不同。Guid可以是数字和字符的随机表示,而UUID包含诸如日期/时间和MAC地址之类的信息。 - Idan
显示剩余2条评论

59

注意:虽然.NET Guid和(RFC4122) UUID的字符串表示形式相同,但它们的存储格式不同。对于前三个Guid部分,.NET使用小端字节序。

如果您正在传输字节(例如作为base64),则不能只使用Guid.ToByteArray()并进行编码。您需要Array.Reverse前三部分(Data1-3)。

我是这样做的:

var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);

有关.NET实现细节的具体内容,请参阅此答案

编辑:感谢Jeff Walker、Code Ranger指出,内部实现与进出字节数组构造函数和ToByteArray()的格式无关。


1
注意:我意识到原帖作者可能是指Guid(因为它是针对.idl文件的),但这里我遇到了这个问题。所以,这里提供给你们,必应和谷歌用户们。 - Ben Mosher
1
我无法测试这个,但你确定应该检查BitConverter.IsLittleEndian而不是总是反转吗?Guid.ToByteArray()的文档将字节顺序指定为小端,且构造函数匹配。GUID的规范是小端。我认为这应该独立于机器字节顺序。 - Jeff Walker Code Ranger
@JeffWalkerCodeRanger:来自Eric Lippert,很久以前的文章:http://blogs.msdn.com/b/ericlippert/archive/2004/05/25/141525.aspx - Ben Mosher
我不认为Eric Lippert的链接回答了这个问题。看着Mono代码(https://github.com/mono/mono/blob/master/mcs/class/corlib/System/Guid.cs),我觉得他们总是假设字节按照小端序排列,而不考虑本地字节序。这符合我的理解,如果它依赖于平台,它将无法匹配MS API或规范的语义。从反汇编的mscorelib来看,它似乎也假定数组中的字节按照小端序排列。 - Jeff Walker Code Ranger
看起来你是对的。虽然内部存储格式是大小端敏感的,但构造函数和 ToByteArray 不是;它们始终是小端的。接下来进行编辑。 - Ben Mosher
显示剩余3条评论

3
这里有一个客户端“顺序guid”的解决方案。 http://www.pinvoke.net/default.aspx/rpcrt4.uuidcreate
using System;
using System.Runtime.InteropServices;


namespace MyCompany.MyTechnology.Framework.CrossDomain.GuidExtend
{
    public static class Guid
    {

        /*

        Original Reference for Code:
        http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html

        */


        [DllImport("rpcrt4.dll", SetLastError = true)]
        static extern int UuidCreateSequential(out System.Guid guid);

        public static System.Guid NewGuid()
        {
            return CreateSequentialUuid();
        }


        public static System.Guid CreateSequentialUuid()
        {
            const int RPC_S_OK = 0;
            System.Guid g;
            int hr = UuidCreateSequential(out g);
            if (hr != RPC_S_OK)
                throw new ApplicationException("UuidCreateSequential failed: " + hr);
            return g;
        }


        /*

        Text From URL above:

        UuidCreateSequential (rpcrt4)

        Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
        To create a page in a module other than rpcrt4, prefix the name with the module name and a period.
        . Summary
        Creates a new UUID 
        C# Signature:
        [DllImport("rpcrt4.dll", SetLastError=true)]
        static extern int UuidCreateSequential(out Guid guid);


        VB Signature:
        Declare Function UuidCreateSequential Lib "rpcrt4.dll" (ByRef id As Guid) As Integer


        User-Defined Types:
        None.

        Notes:
        Microsoft changed the UuidCreate function so it no longer uses the machine's MAC address as part of the UUID. Since CoCreateGuid calls UuidCreate to get its GUID, its output also changed. If you still like the GUIDs to be generated in sequential order (helpful for keeping a related group of GUIDs together in the system registry), you can use the UuidCreateSequential function.

        CoCreateGuid generates random-looking GUIDs like these:

        92E60A8A-2A99-4F53-9A71-AC69BD7E4D75
        BB88FD63-DAC2-4B15-8ADF-1D502E64B92F
        28F8800C-C804-4F0F-B6F1-24BFC4D4EE80
        EBD133A6-6CF3-4ADA-B723-A8177B70D268
        B10A35C0-F012-4EC1-9D24-3CC91D2B7122



        UuidCreateSequential generates sequential GUIDs like these:

        19F287B4-8830-11D9-8BFC-000CF1ADC5B7
        19F287B5-8830-11D9-8BFC-000CF1ADC5B7
        19F287B6-8830-11D9-8BFC-000CF1ADC5B7
        19F287B7-8830-11D9-8BFC-000CF1ADC5B7
        19F287B8-8830-11D9-8BFC-000CF1ADC5B7



        Here is a summary of the differences in the output of UuidCreateSequential:

        The last six bytes reveal your MAC address 
        Several GUIDs generated in a row are sequential 
        Tips & Tricks:
        Please add some!

        Sample Code in C#:
        static Guid UuidCreateSequential()
        {
           const int RPC_S_OK = 0;
           Guid g;
           int hr = UuidCreateSequential(out g);
           if (hr != RPC_S_OK)
             throw new ApplicationException
               ("UuidCreateSequential failed: " + hr);
           return g;
        }



        Sample Code in VB:
        Sub Main()
           Dim myId As Guid
           Dim code As Integer
           code = UuidCreateSequential(myId)
           If code <> 0 Then
             Console.WriteLine("UuidCreateSequential failed: {0}", code)
           Else
             Console.WriteLine(myId)
           End If
        End Sub




        */








    }
}

关键词:创建顺序UUID 顺序UUID


0

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接