这两种字符串转换方式有什么区别System.Guid?是否有理由选择其中一个?
var myguid = Guid.Parse("9546482E-887A-4CAB-A403-AD9C326FFDA5");
Run Code Online (Sandbox Code Playgroud)
要么
var myguid = new Guid("9546482E-887A-4CAB-A403-AD9C326FFDA5");
Run Code Online (Sandbox Code Playgroud)
Jak*_*cki 79
快速浏览反射器可以发现两者几乎相同.
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;
}
Run Code Online (Sandbox Code Playgroud)
Ree*_*sey 23
使用最易读的版本.两者的实现几乎完全相同.
唯一真正的区别是构造函数Guid.Empty在尝试解析之前初始化为自己.但是,有效代码是相同的.
话虽如此,如果Guid来自用户输入,那么Guid.TryParse将比任一选项更好.如果这Guid是硬编码的,并且始终有效,则上述任何一种都是完全合理的选择.
tom*_*ska 10
我尝试了一个百万的guid和Guid.Parse的表现似乎是一个微不足道的速度.它在我的电脑上制作了10-20毫秒的差异800毫秒的总创作量.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
并输出:
新Guid():804毫秒
Guid.Parse():791毫秒
| 归档时间: |
|
| 查看次数: |
20818 次 |
| 最近记录: |