我正在尝试实现Nullable类型。但是下面提到的代码不支持值类型数据类型的空值。
using System;
using System.Runtime;
using System.Runtime.InteropServices;
namespace Nullable
{
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Nullable<T> 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>(T value)
{
return new Nullable<T>(value);
}
public static explicit operator T(Nullable<T> value)
{
return value.Value;
}
}
}当我试图将值赋值为null时,它会抛出一个错误“不能将null转换为'Nullable.Nullable‘,因为它是一个不可空的值类型”。
我要做些什么来解决这个问题?
发布于 2014-09-02 17:41:28
将null分配给Nullable<T>只是分配new Nullable<T>()的语法糖,它是C#语言的一部分,您不能将该特性添加到自定义类型中。
C#规范
4.1.10可空类型 可空类型可以表示其基础类型的所有值加上一个额外的空值。可空类型是写T?,其中T是基础类型。这个语法是System.Nullable的缩写,这两种形式可以互换使用。6.1.5零文本转换 从空文字到任何可空类型存在隐式转换。此转换产生给定可空类型的空值(§4.1.10)。
发布于 2014-09-02 17:43:49
你不能这么做。
Nullable是一个特例。它在CLR级别上有特殊的处理(这不是一个纯C#语言特性,特别是,CLR支持特殊的装箱/取消装箱零标签场景)。
发布于 2014-09-02 18:24:04
您将本地的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;}
}https://stackoverflow.com/questions/25629207
复制相似问题