【问题标题】:How can I convert string to Guid? [duplicate]如何将字符串转换为 Guid? [复制]
【发布时间】:2015-11-27 09:18:20
【问题描述】:

我有像"e2ddfa02610e48e983824b23ac955632" 这样的字符串类型值。我需要添加 - 在这段代码中意味着在 Guid 中转换。

EntityKey = "e2ddfa02610e48e983824b23ac955632";
Id = (Guid)paymentRecord.EntityKey;

【问题讨论】:

  • 是哪一个? C# 还是 C++(CLI)?

标签: c# c++-cli guid


【解决方案1】:

只是一个简单的创作:

  String source = "e2ddfa02610e48e983824b23ac955632";

  Guid result = new Guid(source);

【讨论】:

  • Id = new Guid(paymentRecord.EntityKey),出现错误“无法将对象转换为字节[]”
  • @Kapil Garg:paymentRecord.EntityKey 的类型是什么?即paymentRecord.EntityKey.GetType().Name?
【解决方案2】:

你可以这样做:

Guid guid;
if (Guid.TryParse("e2ddfa02610e48e983824b23ac955632", out guid))
{
    // succeed...
}
else
{
    // failed...
}

编辑:就像@Silvermind 所说,如果你知道输入的格式,你可以在你的情况下使用Guid.TryParseExact"N" 格式。

【讨论】:

  • 既然你知道"N"的格式,我建议添加它。
【解决方案3】:

用于将string 解析为Guid。你可以这样做:

var guid= "e2ddfa02610e48e983824b23ac955632";
var result= Guid.ParseExact(guid,"N")

或者,如果您更喜欢在尝试解析中使用它。你也可以这样做:

Guid result;
if(Guid.TryParseExact(guid,"N",out result))
{
    //Do something
}

“N”是一种格式,表示字符串为32位不带“-”的格式

参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 2010-12-14
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多