C#中的结构真的不能为空吗? [英] Can structs really not be null in C#?

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

问题描述

下面是一些代码,演示了我无法将结构类型声明和初始化为 null.Nullable 类型是一个结构体,为什么我可以设置它为空?

Below is some code that demonstrates I cannot declare and initialize a struct type as null. The Nullable type is a struct, so why am I able to set it to null?

Nullable<bool> b = null;
if (b.HasValue)
{
    Console.WriteLine("HasValue == true");
}

//Does not compile...
Foo f = null;
if (f.HasValue)
{
    Console.WriteLine("HasValue == true");
}

其中 Foo 定义为

public struct Foo
{
    private bool _hasValue;
    private string _value;

    public Foo(string value)
    {
        _hasValue = true;
        _value = value;
    }

    public bool HasValue
    {
        get { return _hasValue; }
    }

    public string Value
    {
        get { return _value; }
    }
}

问题已得到解答(见下文).为了澄清,我将发布一个示例.C# 代码:

The question has been answered (see below). To clarify I'll post an example. The C# code:

using System;

class Program
{
    static void Main(string[] args)
    {
        Nullable<bool> a;
        Nullable<bool> b = null;
    }
}

产生以下IL:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       10 (0xa)
  .maxstack  1
  .locals init ([0] valuetype [mscorlib]System.Nullable`1<bool> a,
           [1] valuetype [mscorlib]System.Nullable`1<bool> b)
  IL_0000:  nop
  IL_0001:  ldloca.s   b
  IL_0003:  initobj    valuetype [mscorlib]System.Nullable`1<bool>
  IL_0009:  ret
} // end of method Program::Main

a 和 b 被声明,但只有 b 被初始化.

a and b are declared, but only b is initialized.

推荐答案

C# 编译器为您提供了一些糖,因此您确实在这样做:

The C# compiler provides you with a bit of sugar so you really are doing this:

Nullable<bool> b = new Nullable<bool>();

这里是语法糖

bool? b = null;    
if (b ?? false) 
{
   b = true;
}

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

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