C# how to create a Guid value?

后端 未结 11 2113
旧时难觅i
旧时难觅i 2020-11-27 09:58

One field of our struct is Guid type. How to generate a valid value for it?

相关标签:
11条回答
  • 2020-11-27 10:40
    var guid = new Guid();
    

    Hey, its a 'valid', although not very useful, Guid.

    (the guid is all zeros, if you don't know. Sometimes this is needed to indicate no guid, in cases where you don't want to use a nullable Guid)

    0 讨论(0)
  • 2020-11-27 10:40

    There's also ShortGuid - A shorter and url friendly GUID class in C#. It's available as a Nuget. More information here.

    PM> Install-Package CSharpVitamins.ShortGuid
    

    Usage:

    Guid guid = Guid.NewGuid();
    ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid
    Console.WriteLine(sguid1);
    Console.WriteLine(sguid1.Guid);
    

    This produces a new guid, uses that guid to create a ShortGuid, and displays the two equivalent values in the console. Results would be something along the lines of:

    ShortGuid: FEx1sZbSD0ugmgMAF_RGHw 
    Guid:      b1754c14-d296-4b0f-a09a-030017f4461f
    
    0 讨论(0)
  • 2020-11-27 10:45
    System.Guid desiredGuid = System.Guid.NewGuid();
    
    0 讨论(0)
  • 2020-11-27 10:49

    Guid.NewGuid() creates a new random guid.

    0 讨论(0)
  • 2020-11-27 10:52

    Alternately, if you are using SQL Server as your database you can get your GUID from the server instead. In TSQL:

    //Retrive your key ID on the bases of GUID 
    
    declare @ID as uniqueidentifier
    
    SET @ID=NEWID()
    insert into Sector(Sector,CID)
    
    Values ('Diry7',@ID)
    
    
    select SECTORID from sector where CID=@ID
    
    0 讨论(0)
提交回复
热议问题