简体   繁体   English

知道字符串是long还是Guid的最佳方法是什么?

[英]What is the best way to know if a string is a long or a Guid?

I have some strings in a text files representing object ids, sometimes the id is a long and other is a Guid, and I need to parse them. 我在文本文件中有一些表示对象ID的字符串,有时ID是一个很长的字符串,而另一个是Guid,我需要解析它们。

The quick answer is obvious, for example trying to parse a Guid and it if fails, try to parse a long, but. 快速答案是显而易见的,例如,尝试解析Guid,但如果失败,则尝试解析长,但是。 Is there any good way ( elegant solution ) to know if a certain string is a long or a Guid? 有什么好办法( 优雅的解决方案 )来知道某个字符串是长字符串还是Guid字符串?

  ee02b525-9755-4a07-a46d-37bb5b060fd2 (Guid)
  -48765 (long)

Thanks in advance. 提前致谢。

The quick answer is obvious, for example trying to parse a Guid and it if fails, try to parse a long, but. 快速答案是显而易见的,例如,尝试解析Guid,但如果失败,则尝试解析长,但是。 Is there any good way (elegant solution) to know if a certain string is a long or a Guid? 有什么好办法(优雅的解决方案)来知道某个字符串是长字符串还是Guid字符串?

No. long.TryParse and Guid.TryParse is the way to go. 不行。long.TryParseGuid.TryParse是要走的路。 Another possibility is to test if the string contains - but not in the beginning: 另一种可能性是测试字符串是否包含-但不在开头:

someString.IndexOf("-") > 1

This is a strong indication that this string is not an Int64. 这强烈表明此字符串不是Int64。 It could be a Guid. 可能是个向导。 But it could be anything else. 但这可能是其他任何事情。 Of course if you know that there can only be Guids and longs in this file it could be a strong indication. 当然,如果您知道此文件中只能包含Guid和long,则可能是一个有力的指示。

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

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