C#中:如果测试字符串是不引发异常一个GUID? [英] C#: Test if string is a guid without throwing exceptions?

查看:229
本文介绍了C#中:如果测试字符串是不引发异常一个GUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试将字符串转换为GUID,但我不想依赖捕捉异常(

I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions (


  • 性能方面的原因 - 异常昂贵

  • 可用性原因 - 调试器弹出

  • 设计原因 - 预期也不例外

在换句话说,code:

In other words the code:

public static Boolean TryStrToGuid(String s, out Guid value)
{
    try
    {
        value = new Guid(s);
        return true;
    }
    catch (FormatException)
    {
        value = Guid.Empty;
        return false;
    }
}

是不适合的。

我会尝试使用正则表达式,但由于GUID可以括号包裹,包裹着护具,没有包装,使得它很难。

I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard.

此外,我想一定GUID值是无效的(?)

Additionally, I thought certain Guid values are invalid(?)

更新1

<一个href=\"http://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#137829\">ChristianK有一个好主意,只捕获 FormatException ,而不是全部。改变问题的code样品包括建议。

ChristianK had a good idea to catch only FormatException, rather than all. Changed the question's code sample to include suggestion.

更新2

为什么要担心抛出的异常?我真的期待无效的GUID所有的时候?

Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often?

答案的的。这就是为什么我使用TryStrToGuid - 我上午期待坏数据

The answer is yes. That is why I am using TryStrToGuid - I am expecting bad data.

示例1 可以通过指定的命名空间扩展附加一个GUID到一个文件夹名称。我可能会解析文件夹名称,检查是否最终文本后的 是一个GUID。

Example 1 Namespace extensions can be specified by appending a GUID to a folder name. I might be parsing folder names, checking to see if the text after the final . is a GUID.

c:\Program Files
c:\Program Files.old
c:\Users
c:\Users.old
c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666}
c:\Windows
c:\Windows.old

例2 我可能会运行一个负载很重的web服务器要检查一些调回数据的有效性。我不希望无效数据占用资源幅度高于它需要2-3个数量级。

Example 2 I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be.

例3 我可能会被解析由用户输入的搜索前pression。

Example 3 I might be parsing a search expression entered by a user.

如果他们进入GUID的我想专门处理它们(如专门为搜索对象,或突出显示并格式化响应文本的特定搜索词。)

If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.)

更新3 - 性能基准测试

测试转换万善的GUID,10000坏的GUID。

Test converting 10,000 good Guids, and 10,000 bad Guids.

Catch FormatException:
   10,000 good:     63,668 ticks
   10,000 bad:   6,435,609 ticks

Regex Pre-Screen with try-catch:
   10,000 good:    637,633 ticks
   10,000 bad:     717,894 ticks

COM Interop CLSIDFromString
   10,000 good:    126,120 ticks
   10,000 bad:      23,134 ticks

P.S。我不应该来证明的问题。

推荐答案

性能基准

Catch exception:
   10,000 good:    63,668 ticks
   10,000 bad:  6,435,609 ticks

Regex Pre-Screen:
   10,000 good:   637,633 ticks
   10,000 bad:    717,894 ticks

COM Interop CLSIDFromString
   10,000 good:   126,120 ticks
   10,000 bad:     23,134 ticks

COM Intertop(最快)答:

/// <summary>
/// Attempts to convert a string to a guid.
/// </summary>
/// <param name="s">The string to try to convert</param>
/// <param name="value">Upon return will contain the Guid</param>
/// <returns>Returns true if successful, otherwise false</returns>
public static Boolean TryStrToGuid(String s, out Guid value)
{
   //ClsidFromString returns the empty guid for null strings   
   if ((s == null) || (s == ""))   
   {      
      value = Guid.Empty;      
      return false;   
   }

   int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value);
   if (hresult >= 0)
   {
      return true;
   }
   else
   {
      value = Guid.Empty;
      return false;
   }
}


namespace PInvoke
{
    class ObjBase
    {
    	/// <summary>
    	/// This function converts a string generated by the StringFromCLSID function back into the original class identifier.
    	/// </summary>
    	/// <param name="sz">String that represents the class identifier</param>
    	/// <param name="clsid">On return will contain the class identifier</param>
    	/// <returns>
    	/// Positive or zero if class identifier was obtained successfully
    	/// Negative if the call failed
    	/// </returns>
    	[DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]
    	public static extern int CLSIDFromString(string sz, out Guid clsid);
    }
}



底线:如果你需要检查一个字符串是否是一个GUID,你关心性能,使用COM互操作。

Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop.

如果您需要在重新串presentation一个GUID转换为一个GUID,使用

If you need to convert a guid in String representation to a Guid, use

new Guid(someString);

这篇关于C#中:如果测试字符串是不引发异常一个GUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆