2011-08-02 142 views
49

这两种将字符串转换为System.Guid的方法有什么区别?是否有理由相互选择一个呢?Guid.Parse()或新的Guid() - 有什么区别?

var myguid = Guid.Parse("9546482E-887A-4CAB-A403-AD9C326FFDA5"); 

var myguid = new Guid("9546482E-887A-4CAB-A403-AD9C326FFDA5"); 
+6

在什么样的条件? – raym0nd

+3

你也可以使用:Guid.TryParse() –

回答

62

在Reflector中快速浏览一下,发现两者几乎相同。

public Guid(string g) 
{ 
    if (g == null) 
    { 
     throw new ArgumentNullException("g"); 
    } 
    this = Empty; 
    GuidResult result = new GuidResult(); 
    result.Init(GuidParseThrowStyle.All); 
    if (!TryParseGuid(g, GuidStyles.Any, ref result)) 
    { 
     throw result.GetGuidParseException(); 
    } 
    this = result.parsedGuid; 
} 

public static Guid Parse(string input) 
{ 
    if (input == null) 
    { 
     throw new ArgumentNullException("input"); 
    } 
    GuidResult result = new GuidResult(); 
    result.Init(GuidParseThrowStyle.AllButOverflow); 
    if (!TryParseGuid(input, GuidStyles.Any, ref result)) 
    { 
     throw result.GetGuidParseException(); 
    } 
    return result.parsedGuid; 
} 
+0

感谢您的回复。我真的在寻找“他们在工作方式上的差异”。 – brennazoon

+0

看起来使用的GuidParseThrowStyle有明显的区别,所以可以为其他人不会输入的错误输入。 – Triynko

+0

@Triynko:如果你看代码,你会发现它们都是出于同样的原因。唯一的区别是,如果抛出了'OverflowException',它将在'Guid.Parse'的情况下被封装在'FormatException'中。 –

4

我会去与TryParse。它不会抛出异常。

+20

我不会认为这样的原因。有些情况下你想要一个例外情况和你不需要的场景。根据场景选择适当的方法更重要。 –

+0

带有可能有空字符串的db的+1,这是一种简单的方法来解析guid并在字符串为空时获取Guid.Empty。 – ashes999

18

使用最易读的版本。两者的实施方式几乎完全相同。

唯一真正的区别是构造函数在尝试解析之前将其自身初始化为Guid.Empty。但是,有效的代码是相同的。

也就是说,如果Guid来自用户输入,那么Guid.TryParse会比任一选项更好。如果这个Guid是硬编码的并且总是有效的,以上任何一个都是完全合理的选项。

9

我尝试过在一个千变万化的guid和Guid.Parse上表现的速度似乎微不足道。它在我的电脑上创造了总计800毫秒的10-20毫秒的差异。

public class Program 
{ 
    public static void Main() 
    { 
     const int iterations = 1000 * 1000; 
     const string input = "63559BC0-1FEF-4158-968E-AE4B94974F8E"; 

     var sw = Stopwatch.StartNew(); 
     for (var i = 0; i < iterations; i++) 
     { 
      new Guid(input); 
     } 
     sw.Stop(); 

     Console.WriteLine("new Guid(): {0} ms", sw.ElapsedMilliseconds); 

     sw = Stopwatch.StartNew(); 
     for (var i = 0; i < iterations; i++) 
     { 
      Guid.Parse(input); 
     } 
     sw.Stop(); 

     Console.WriteLine("Guid.Parse(): {0} ms", sw.ElapsedMilliseconds); 
    } 
} 

输出:

新的GUID():804毫秒

Guid.Parse():791毫秒