【发布时间】:2015-04-11 04:15:19
【问题描述】:
为什么null可以像这样隐式转换为System.Nullable<T>:
int? val = null;
但是自定义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;
}
}
下面的测试代码,编译错误
Nullable<int> x = null; //ERROR Cannot convert null to 'Nullable<int>' because it is a non-nullable value type
【问题讨论】:
-
因为 System.Nullable 在 C# 语言中得到特殊处理。
-
@default.kramer 有什么详细信息吗?
-
@Asad 这是一个 Nullable
装箱或拆箱问题,所以我认为它不重复 -
还有其他特殊处理的例子如lifted operators and conversions。