如何在.NET中的引擎盖下实现的可空类型? [英] how are nullable types implemented under the hood in .net?

查看:154
本文介绍了如何在.NET中的引擎盖下实现的可空类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们自己的乔恩斯基特的 C#深入,他讨论了3种方式来模拟一个'空'的值类型:

In our own Jon Skeet's C# in depth, he discusses the 3 ways to simulate a 'null' for value types:


  • 魔法值(例如最早可能日期时间取为'空')

  • 引用类型的包装

  • 布尔标志

要提及的是空类型使用第三种方法。究竟如何做到可空类型的发动机罩下工作吗?

It is mentioned that nullable types use the third method. How exactly do nullable types work under the hood?

推荐答案

最后,他们都只是一个布尔标志的通用结构 - 除非有特殊拳击规则。因为结构是(默认)初始化为零,所述布尔默认为假(没有值):

Ultimately, they are just a generic struct with a bool flag - except with special boxing rules. Because structs are (by default) initialized to zero, the bool defaults to false (no value):

public struct Nullable<T> where T : struct {
    private readonly T value;
    private readonly bool hasValue;
    public Nullable(T value) {
        this.value = value;
        hasValue = true;
    }
    public T Value {
        get {
           if(!hasValue) throw some exception ;-p
           return value;
        }
    }
    public T GetValueOrDefault() { return value; }
    public bool HasValue {get {return hasValue;}}
    public static explicit operator T(Nullable<T> value) {
        return value.Value; }
    public static implicit operator Nullable<T>(T value) {
        return new Nullable<T>(value); }
}

额外差异,虽然:

Extra differences, though:


  • 特殊拳击规则(您无法正常做到这一点)

  • 特殊C#的规则比较空等

  • 解禁运营商在C#(和.NET通过 EqualityComparer&LT; T&GT; 的Comparer&LT; T&GT; 等)

  • 泛型类型约束
  • 特殊规则(以prevent 可空&LT;可空&LT; T&GT;&GT;

  • special boxing rules (you can't normally do this)
  • special C# rules for comparing to null etc
  • "lifted" operators in C# (and in .NET via EqualityComparer<T>, Comparer<T> etc)
  • special rules on generic type constraints (to prevent Nullable<Nullable<T>>)

这篇关于如何在.NET中的引擎盖下实现的可空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆