Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将字符串值转换回GUID值_C#_Guid - Fatal编程技术网

C# 将字符串值转换回GUID值

C# 将字符串值转换回GUID值,c#,guid,C#,Guid,我有一个存储在隐藏变量中的guid值。 例如(303427ca-2a5c-df11-a391-005056b73dd7) 现在我如何将这个隐藏字段中的值转换回GUID值(因为我要调用的方法需要一个GUID值) 多谢各位 string strGuid; strGuid = (your guid here); Guid guid = new Guid(strGuid); Guid具有字符串Guid的构造函数 Guid guid = new Guid(myStringGuid

我有一个存储在隐藏变量中的guid值。 例如(303427ca-2a5c-df11-a391-005056b73dd7)

现在我如何将这个隐藏字段中的值转换回GUID值(因为我要调用的方法需要一个GUID值)

多谢各位

    string strGuid;
    strGuid = (your guid here);
    Guid guid = new Guid(strGuid);

Guid具有字符串Guid的构造函数

Guid guid = new Guid(myStringGuid);

新Guid(myHiddenFieldString)

只需使用重载构造函数:

try
{
  Guid guid = new Guid("{D843D80B-F77D-4655-8A3E-684CC35B26CB}");
}
catch (Exception ex) // There might be a more appropriate exception to catch
{
  // Do something here in case the parsing fails.
}

我认为可以简单地做到以下几点:

Guid MyGuid = new Guid(stringValue);

通过将Guid存储在字符串中,您可以非常轻松地对付攻击者。例如,在分页文件中查找很简单。将其存储在Guid中,一举两得。

在.NET4之后的版本中,您还可以使用:

Guid myGuid = Guid.Parse(myGuidString); 

只是编码偏好的问题,但有些人觉得这更直观。

这肯定是最简单的method@espais:是的,当我看到事情变得如此简单时,我有时会感到害怕。值得注意的是,GUID没有可用的TryParse,因此您可能希望将其包装在try/catch块中。感谢@Peter Kelly指出这一点。我更新了我的答案以添加此建议。