简体   繁体   English

C# - 将字符串转换为可为空的 Guid?

[英]C# - Converting string into nullable Guid?

Is there an easier way of converting a string into a Guid?有没有更简单的方法将字符串转换为Guid? ? ? Just now I have this code:刚才我有这个代码:

if (Guid.TryParse(request.QueryStringParameters["key"], out Guid result))
{
    whateverFunction(result);
}
else
{
    whateverFunction(null);
}

I was hoping there would be an easier way such as casting to (Guid?) or doing new Guid?() however neither of them seem to work.我希望有一种更简单的方法,例如转换为(Guid?)或执行new Guid?()但它们似乎都不起作用。 This needs to happen a lot of times in my program, obviously I can just put it in a function and that would be fine but hoping there is a cleaner way of doing this.这需要在我的程序中发生很多次,显然我可以将它放在 function 中,这很好,但希望有一种更清洁的方法来做到这一点。

Alternatively, you can write your code like this:或者,您可以像这样编写代码:

var nullableGuid = Guid.TryParse(request.QueryStringParameters["key"], out var result)
    ? result
    : (Guid?)null;

whateverFunction(nullableGuid);

Just write your own method:只需编写自己的方法:

public Guid? TryParseGuid(string input)
{
   if (Guid.TryParse(input, out Guid result))
   {
       return result;
   }
   else
   {
       return null;
   }
}

You can use it the following way:您可以通过以下方式使用它:

whateverFunction(TryParseGuid(request.QueryStringParameters["key"]));

if your application is heavily used string guids, then use extension instead:如果您的应用程序大量使用字符串 guid,请改用扩展名:

public static class AppExtension
{
    public static Guid? ToGuid(this string source)
    {
        return Guid.TryParse(source , out Guid result) ? (Guid?) result : null;
    }
}

usage would be:用法是:

var guidStr = "6b97c671-8cc4-4712-b3df-9dad09321a36";
var guid = guidStr.ToGuid();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM