为什么我可以将 null 分配给 Type "struct Nullable<T>" 的值而不是我的结构?
Why can I assign null to value of Type "struct Nullable<T>" but not to my struct?
我知道可空值类型的机制。
但是,我对以下内容感兴趣:
可空值类型正在使用结构(来自 https://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e)
public struct Nullable<T> where T : struct {
public Nullable(T value) {
/* ... */
}
public bool HasValue {get;}
public T Value {get;}
}
我可以这样用
Nullable<int> i = null;
现在,我以相同的方式创建自己的 Nullable-Struct:
public struct MyNullable<T> where T : struct {
public MyNullable(T value) {
/* ... */
}
public bool HasValue {get;}
public T Value {get;}
}
为什么我做不到
MyNullable<int> i = null;
现在?
我知道,struct 的值不能为 null - 但为什么 struct Nullable 的值可以为 null?允许这样做的机制在哪里?
Where is the mechanism which allows this?
在 C# 编译器本身。 Nullable<T>
是一种特殊类型,有很多额外的规则,包括如何处理 null
(比较和赋值),以及如何处理运算符(参见:"lifted operators")。
在运行时中有也支持Nullable<T>
,用于特殊的"boxing"规则。
您无法在自己的代码中模拟 Nullable<T>
,因为这些特殊规则您无法表达。
我知道可空值类型的机制。 但是,我对以下内容感兴趣:
可空值类型正在使用结构(来自 https://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e)
public struct Nullable<T> where T : struct {
public Nullable(T value) {
/* ... */
}
public bool HasValue {get;}
public T Value {get;}
}
我可以这样用
Nullable<int> i = null;
现在,我以相同的方式创建自己的 Nullable-Struct:
public struct MyNullable<T> where T : struct {
public MyNullable(T value) {
/* ... */
}
public bool HasValue {get;}
public T Value {get;}
}
为什么我做不到
MyNullable<int> i = null;
现在?
我知道,struct 的值不能为 null - 但为什么 struct Nullable 的值可以为 null?允许这样做的机制在哪里?
Where is the mechanism which allows this?
在 C# 编译器本身。 Nullable<T>
是一种特殊类型,有很多额外的规则,包括如何处理 null
(比较和赋值),以及如何处理运算符(参见:"lifted operators")。
在运行时中有也支持Nullable<T>
,用于特殊的"boxing"规则。
您无法在自己的代码中模拟 Nullable<T>
,因为这些特殊规则您无法表达。