为什么null隐式转换为System.Nullable<T>这样:
int? val = null;
Run Code Online (Sandbox Code Playgroud)
但是自定义Nullable<T>(从.net引用源修改)无法分配null,是否有一些编译魔术?谁能告诉我更多的内部暗示?
[Serializable]
public struct Nullable<T> where T : struct
{
private bool hasValue;
internal T value;
public Nullable(T value)
{
this.value = value;
this.hasValue = true;
}
public bool HasValue
{
get
{
return hasValue;
}
}
public T Value
{
get
{
if (!HasValue)
{
throw new Exception();
}
return value;
}
}
public T GetValueOrDefault()
{
return value;
}
public T GetValueOrDefault(T defaultValue)
{
return HasValue ? value : defaultValue;
}
public override bool Equals(object other)
{
if (!HasValue) return other == null;
if (other == null) return false;
return value.Equals(other);
}
public override int GetHashCode()
{
return HasValue ? value.GetHashCode() : 0;
}
public override string ToString()
{
return HasValue ? 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;
}
}
Run Code Online (Sandbox Code Playgroud)
下面测试代码,编译错误
Nullable<int> x = null; //ERROR Cannot convert null to 'Nullable<int>' because it is a non-nullable value type
Run Code Online (Sandbox Code Playgroud)
C#5.0规范的6.1.5节:
6.1.5空文字转换
从空文字到任何可空类型存在隐式转换.此转换生成给定可空类型的空值(第4.1.10节).
请注意,此编译器提供的隐式转换仅存在于可空类型中.您定制的自定义Nullable<T>类型不是C#规范定义的可空类型.它只是你声明的一些结构体,它具有许多内置Nullable<T>类型的特性(在引用的4.1.10节中描述),但根据C#中的定义,它实际上并不是"可空的".
| 归档时间: |
|
| 查看次数: |
1198 次 |
| 最近记录: |