.NET Short Unique Identifier

前端 未结 23 1119
忘掉有多难
忘掉有多难 2020-12-07 11:27

I need a unique identifier in .NET (cannot use GUID as it is too long for this case).

Do people think that the algorithm used here is a good candidate or do you have

23条回答
  •  一整个雨季
    2020-12-07 12:14

    If you dont need to type the string you could use the following:

    static class GuidConverter
    {
        public static string GuidToString(Guid g)
        {
            var bytes = g.ToByteArray();
            var sb = new StringBuilder();
            for (var j = 0; j < bytes.Length; j++)
            {
                var c = BitConverter.ToChar(bytes, j);
                sb.Append(c);
                j++;
            }
            return sb.ToString();
        }
    
        public static Guid StringToGuid(string s) 
            => new Guid(s.SelectMany(BitConverter.GetBytes).ToArray());
    }
    

    This will convert the Guid to a 8 character String like this:

    {b77a49a5-182b-42fa-83a9-824ebd6ab58d} --> "䦥띺ᠫ䋺ꦃ亂檽趵"

    {c5f8f7f5-8a7c-4511-b667-8ad36b446617} --> "엸詼䔑架펊䑫ᝦ"

提交回复
热议问题