Nullable 实现

我正在尝试实现Nullable类型。 但是下面提到的代码不支持valuetype数据类型的空值。

using System; using System.Runtime; using System.Runtime.InteropServices; namespace Nullable { [Serializable, StructLayout(LayoutKind.Sequential)] public struct Nullable where T : struct { private bool hasValue; public bool HasValue { get { return hasValue; } } internal T value; public Nullable(T value) { this.value = value; this.hasValue = true; } public T Value { get { if (!this.hasValue) { new InvalidOperationException("No value assigned"); } return this.value; } } public T GetValueOrDefault() { return this.value; } public T GetValueOrDefault(T defaultValue) { if (!this.HasValue) { return defaultValue; } return this.value; } public override bool Equals(object obj) { if (!this.HasValue) { return obj == null; } if (obj == null) { return false; } return this.value.Equals(obj); } public override int GetHashCode() { if (!this.hasValue) { return 0; } return this.value.GetHashCode(); } public override string ToString() { if (!this.hasValue) { return string.Empty; } return this.value.ToString(); } public static implicit operator Nullable(T value) { return new Nullable(value); } public static explicit operator T(Nullable value) { return value.Value; } } } 

当我尝试将值赋值为null时,它会抛出一个错误“无法将null转换为’Nullable.Nullable’,因为它是一个不可为空的值类型”

我需要做些什么来解决这个问题?

null Nullable只是分配new Nullable()的语法糖,它是C#语言的一部分,并且您无法将该function添加到自定义类型。

C#规范,

4.1.10可空类型

可空类型可以表示其基础类型的所有值加上额外的空值。 可空类型写为T ?,其中T是基础类型。 此语法是System.Nullable的简写,这两种forms可以互换使用。

6.1.5空文字转换

存在从null文字到任何可空类型的隐式转换。 此转换生成给定可空类型的空值(第4.1.10节)。

你不能。
Nullable是一个特例。 它在CLR级别上有特殊处理(这不是纯粹的C#语言特性 – 特别是,CLR支持装箱/取消装箱nullables的特殊场景)。

您将自己开发的Nullable声明为struct ,并且struct不可为空。 您应该将其声明为class

此代码应抛出您遇到的相同错误,将Point类型声明从struct切换到class应修复它。

 void Main() { Point p = null; } // Define other methods and classes here struct Point { public int X {get; set;} public int Y {get; set;} }