C#Guid可以为空吗? [英] Can a C# Guid be null?

查看:119
本文介绍了C#Guid可以为空吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有诸如Guid?Nullable<Guid>之类的东西.我有这段代码,它可以编译:

I know there is a such a thing as Guid? and Nullable<Guid>. I have this code and it compiles:

public Contact GetContact(Guid contactId)
{
    if (contactId == null)
    {
        throw new ArgumentNullException(nameof(contactId));
    }

    return _communicationsDbContext.Set<Contact>().Find(contactId);
}

"contactId == null"可以为真吗?

Can "contactId == null" ever be true?

推荐答案

System.Guid是一个结构,不能为null,因为它不是引用类型.我相信对于实现自定义相等运算符的已知struct类型(例如int,Guid等),编译器会将null比较替换为false. (因此,整个比较和throw语句将消失)

System.Guid is a struct, which cannot be null as it is not a reference type. I believe that for known struct types that implement custom equality operator (e.g. int, Guid etc) the compiler will substitute the null comparison with false. (Hence the whole comparison and throw statement will disappear)

对于未实现自定义等于运算符的struct类型,代码将完全无法编译.

For the struct types that do not implement custom equality operator, the code simply won't compile.

尽管如此,这是不必要的.

Nonetheless, it is unnecessary.

请参阅: https://sharplab.io/#v2:EYLgtghgzgLgpgJwDQxASwDYB8ACAGAAhwEYBuAWACgcBmIgJgIGECBvKgzounAFgICyACgDiAVzQATAgHMJkgJRsOXVWgBmBIXKkEAvHoIA7MRgxKYACwQB7AO7G4DgIII5YOEZgA5UxgCiAB4AxnAADjBoNkZCChSUqgC+VIlAA= ==

public void M(Guid guid)
{
    if (guid == null) throw new ArgumentNullException();
}

将被编译为:

// Methods
    .method public hidebysig 
        instance void M (
            valuetype [mscorlib]System.Guid guid
        ) cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 1 (0x1)
        .maxstack 8

        IL_0000: ret
    } // end of method C::M

如您所见,该方法中的第一条指令是return.

As you can see, the first instruction in the method is return.

这篇关于C#Guid可以为空吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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