Können Strukturen in C # wirklich nicht null sein?

Unten ist ein code, der demonstriert, kann ich nicht deklarieren und initialisieren Sie ein struct-Typ als null. Die Null-Werte zulässt Typ ist ein struct, also warum bin ich in der Lage, es auf 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");
}

Wo Foo ist definiert als

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; }
    }
}

Wurde die Frage beantwortet (siehe unten). Um zu klären, poste ich ein Beispiel. Der C# - code:

using System;

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

erzeugt die folgende 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 und b deklariert sind, sondern nur b ist initialisiert.

InformationsquelleAutor der Frage Nate | 2011-05-20

Schreibe einen Kommentar