可空T实作 [英] Nullable<T> implementation
问题描述
我正在尝试实现Nullable类型。但是下面提到的代码不支持valuetype数据类型的空值。
I am trying to implement Nullable type. But below mentioned code doesn't support null value for valuetype datatypes.
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',因为它是非空值类型
When I trying to assign the value as null, it's throwing an error "Cannot convert null to 'Nullable.Nullable' because it is a non-nullable value type"
我必须解决的问题
推荐答案
将 null
分配给 Nullable< T>
只是分配 new Nullable< T>()
的语法糖,它是C#语言的一部分,您不能
Assigning null
to Nullable<T>
is just a syntactic sugar for assigning new Nullable<T>()
, it's part of C# language, and you can't add that feature to you custom type.
C#规范,
> 4.1.10可空类型
可空类型可以表示其基础类型的所有值加上
的附加空值。可空类型写为T ?,其中T是基础类型
。此语法是System.Nullable,
的简写,并且两种形式可以互换使用。
A nullable type can represent all values of its underlying type plus an additional null value. A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable, and the two forms can be used interchangeably.
6.1.5空文字转换
从空文字到任何可空$的隐式转换存在b $ b类型。此转换将产生给定
可为空类型的空值(第4.1.1节)。
An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type.
这篇关于可空T实作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!