[英]How is Nullable<T> different from a similar custom C# struct?
In Nullable micro-optimizations, part one , Eric mentions that Nullable<T>
has a strange boxing behaviour that could not be achieved by a similar user-defined type. 在Nullable微优化(第一部分)中 ,Eric提到
Nullable<T>
具有奇怪的装箱行为 ,而这种行为无法通过类似的用户定义类型实现。
What are the special features that the C# language grants to the predefined Nullable<T>
type? C#语言赋予预定义的
Nullable<T>
类型有哪些特殊功能? Especially the ones that could not be made to work on a MyNullable
type. 特别是那些无法在
MyNullable
类型上工作的MyNullable
。
Of course, Nullable<T>
has special syntactic sugar T?
当然,
Nullable<T>
有特殊的语法糖T?
, but my question is more about semantics. ,但我的问题更多是关于语义。
What I was getting at is: there is no such thing as a boxed nullable . 我得到的是: 没有盒装可空的东西 。 When you box an
int
, you get a reference to a boxed int
. 当你装入一个
int
,你得到一个盒装int
的引用。 When you box an int?
当你装一个
int?
, you get either a null reference or a reference to a boxed int
. ,您获得空引用或对盒装
int
的引用。 You never get a boxed int?
你永远不会得到盒装
int?
. 。
You can easily make your own Optional<T>
struct, but you can't implement a struct that has that boxing behaviour. 您可以轻松地创建自己的
Optional<T>
结构,但不能实现具有该装箱行为的结构。 Nullable<T>
's special behaviour is baked into the runtime. Nullable<T>
的特殊行为被烘焙到运行时。
This fact leads to a number of oddities. 这一事实导致了许多奇怪的事情。 For example:
例如:
C# Reflection: How to get the type of a Nullable<int>? C#反思:如何获取Nullable <int>的类型?
Cannot change type to nullable in generic method 在泛型方法中无法将类型更改为可为空
And FYI there are other ways in which the Nullable<T>
type is "magical". 而且仅供参考,
Nullable<T>
类型还有其他方式是“神奇的”。 For instance, though it is a struct type, it does not satisfy the struct constraint. 例如,尽管它是结构类型,但它不满足结构约束。 There's no way for you to make your own struct that has that property.
您无法创建具有该属性的自己的结构。
I found these two in the C# specifications : 我在C#规范中找到了这两个:
is
operator works on T?
is
运营商在T?
as it would have on T
, and the as
operator can convert to nullable types. T
, as
运算符可以转换为可空类型。 Now, here are the features that I think are not limited to Nullable<T>
: 现在,我认为这些功能不仅限于
Nullable<T>
:
switch
can be of a nullable type. switch
的值可以是可空类型。 I don't think this counts, because switch also accepts user-defined implicit conversions that could be defined on a MyNullable type. Here is what I am not sure about: 这是我不确定的:
C# lifts operators on nullable types. C#提升运营商的可空类型。 For example:
例如:
int? SumNullableInts(int? a, int? b)
{
return a + b;
}
You would have to do a lot of reflection work in MyNullable<T>
to support that, and then the following would compile, where it shouldn't: 你必须在
MyNullable<T>
做很多反射工作来支持它,然后下面的代码将编译,它不应该:
MyNullable<List<string>.Enumerator> SumNullableEnumerators(MyNullable<List<string>.Enumerator> a, MyNullable<List<string>.Enumerator> b)
{
return a + b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.