如何为空< T>从类似的自定义C#结构有什么不同? [英] How is Nullable<T> different from a similar custom C# struct?
问题描述
在可空微的优化,第一部分,埃里克提到,可空< T>
拥有的奇怪的拳击行为的不能由一个类似的用户定义类型来实现。
有什么特殊功能,在C#语言的赠款,以预定义的可空< T>
键入?尤其是无法作出一个 MyNullable
键入
当然,工作的人,可空< T>
具有特殊的语法糖 T
,但我的问题更多的是语义
<? DIV CLASS =h2_lin>解决方案
我是越来越善于为:有没有这样的东西作为一个盒装可为空。当你框中 INT
,你得到的是盒装的 INT
的参考。当你框中 INT?
,你无论是空引用或引用的盒装 INT
。你永远没有盒装 INT
您可以轻松地制作自己的可选<?。 T>
结构,但你无法实现具有拳击的行为结构。 可空< T>
的特殊行为被烤成运行
这实际上导致了一些奇怪的现象。 。例如:
和FYI还有其他的方式,其中可空< T>
类型是神奇。例如,尽管它是一个结构式,它不满足该结构的约束。有没有办法为你做你自己的结构具有这个属性。
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.
What are the special features that the C# language grants to the predefined Nullable<T>
type? Especially the ones that could not be made to work on a MyNullable
type.
Of course, Nullable<T>
has special syntactic sugar 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
. When you box an int?
, you get either a null reference or a reference to a boxed int
. You never get a boxed int?
.
You can easily make your own Optional<T>
struct, but you can't implement a struct that has that boxing behaviour. Nullable<T>
's special behaviour is baked into the runtime.
This fact leads to a number of oddities. For example:
And FYI there are other ways in which the Nullable<T>
type is "magical". 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.
这篇关于如何为空< T>从类似的自定义C#结构有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!