【问题标题】:How can I generate UUID in C#如何在 C# 中生成 UUID
【发布时间】:2012-01-18 15:28:14
【问题描述】:

我正在以编程方式创建一个 .idl 文件。如何以编程方式为接口和方法创建 UUID。

我可以通过编程方式生成 UUID 吗?

【问题讨论】:

  • 你的意思是Guid.NewGuid()

标签: c# .net visual-studio-2008 com uuid


【解决方案1】:

您可能正在寻找System.Guid.NewGuid()

【讨论】:

  • 你也可以做 String UUID = Guid.NewGuid().ToString()
  • GUID 和 UUID 都一样吗?
  • @Uma Shankar Subramani:GUID = 全球唯一标识符,UUID = 全球唯一标识符。同一个概念的不同词。
  • 并且您需要将 GUID 格式化为不同于默认值的字符串,您可以使用接受多个格式说明符之一的 ToString(string format) 重载。
  • 如果您想与一些无法理解小写 UUID 的 MS Build 工具兼容,您可能需要执行 System.Guid.NewGuid().ToString("B").ToUpper()。例如,vdproj setup 项目的 UUID 为大写,如果您将其设为小写,则会引发异常。
【解决方案2】:

注意:虽然 .NET Guid 和 (RFC4122) UUID 的字符串表示形式相同,但 the storage format is not. .NET 以小端字节交换前三个 Guid 部分。

如果您正在传输字节(例如,作为 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);

请参阅this answer 了解具体的 .NET 实现细节。

编辑:感谢 Code Ranger 的 Jeff Walker 指出内部结构与进出字节数组构造函数的字节数组的格式无关,@987654329 @。

【讨论】:

  • 注意:我意识到 OP 可能意味着 Guid(因为它是为 .idl 设计的),但我只是遇到了这个问题。好了,Bingers 和 Google 员工。
  • 我无法测试这个,但你确定你应该检查 BitConverter.IsLittleEndian 而不是总是倒车。 Guid.ToByteArray() 的文档将字节顺序称为小端,并说构造函数匹配。 GUID 的规范是小端。我认为这应该与机器字节顺序无关。
  • @JeffWalkerCodeRanger:来自 Eric Lippert,很久以前:blogs.msdn.com/b/ericlippert/archive/2004/05/25/141525.aspx
  • 我看不出 Eric Lippert 链接如何回答这个问题。查看github.com/mono/mono/blob/master/mcs/class/corlib/System/… 的 Mono 代码,在我看来,无论原生字节序如何,它们总是假设字节是小字节序。这符合我的理解,如果它依赖于平台,它将与 MS api 或规范的语义不匹配。查看反汇编的 mscorelib,似乎假设数组中的字节也是小端顺序。
  • 看来你是对的。虽然内部存储格式是字节序敏感的,但构造函数和ToByteArray 不是;他们总是 lil'-endian。编辑传入。
【解决方案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




        */








    }
}

关键字:CreateSequentialUUID SequentialUUID

【讨论】:

    【解决方案4】:

    我不知道方法;但是,GUID 的类型可以通过以下方式完成:

    Guid iid = System.Runtime.InteropServices.Marshal.GenerateGuidForType(typeof(IFoo));
    

    http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx

    【讨论】:

      【解决方案5】:

      我有一个 GitHub Gist,它在 C# 中使用类似 Java 的 UUID 实现: https://gist.github.com/rickbeerendonk/13655dd24ec574954366

      UUID 可以从最低和最高有效位创建,就像在 Java 中一样。它也暴露了它们。该实现具有到 GUID 的显式转换和从 GUID 的隐式转换。

      【讨论】:

        猜你喜欢
        • 2017-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-05-23
        • 2014-08-13
        相关资源
        最近更新 更多