简体   繁体   English

从不是guid格式的字符串生成GUID

[英]Generate GUID from a string that is not in guid format

I would like to generate a GUID from the input string. 我想从输入字符串生成GUID。 Let's say I have guid received from the user which is 假设我收到了来自用户的guid

81a130d2-502f-4cf1-a376-63edeb000e9f

so I can do: 所以我可以这样做:

 Guid g = Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f");

which is going to parse successfully. 这将成功解析。

But how to make user's life easier and allow to input: 但是如何让用户的生活更轻松,并允许输入:

81a130d2502f4cf1a37663edeb000e9f

which is without dashes, and still convert it to guid. 没有破折号,仍然将其转换为guid。

If I will try to use the same method it's gonna throw the exception complaining on the missing dashed in the guid format. 如果我将尝试使用相同的方法,它将抛出异常抱怨guid格式中丢失的虚线。

Any ideas? 有任何想法吗?

尝试

Guid.ParseExact("81a130d2502f4cf1a37663edeb000e9f", "N");

The in addition to ParseExact (with "N" as the second argument), you could instead use the overload of the Guid constructor that accepts a string; 除了ParseExact (以"N"作为第二个参数)之外,您还可以使用接受字符串的Guid构造函数的重载; it allows you to specify your value without dashes as well. 它允许您指定您的值而不用破折号。

Guid g = new Guid("81a130d2502f4cf1a37663edeb000e9f");

使用ParseExact方法:

Guid.ParseExact("81a130d2502f4cf1a37663edeb000e9f","N")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM