? (可为空)运算符在C# [英] ? (nullable) operator in C#

查看:212
本文介绍了? (可为空)运算符在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是对,现在它可以存储null值类型的数据类型为空的应用操作改变。

What is changed by applying nullable Operator on value type datatype that now it can store null.

推荐答案

正如其他人所说,?仅仅是将其更改为可空&LT速记; T> 。这仅仅是另一个值类型与布尔标志说是否有真的有用的价值,或者它是否是该类型的空值。换句话说,可空< T> 看起来有点像这样:

As others have said, "?" is just shorthand for changing it to Nullable<T>. This is just another value type with a Boolean flag to say whether or not there's really a useful value, or whether it's the null value for the type. In other words, Nullable<T> looks a bit like this:

public struct Nullable<T>
{
    private readonly bool hasValue;
    public bool HasValue { get { return hasValue; } }

    private readonly T value;
    public T value
    {
        get
        {
            if (!hasValue)
            {
                throw new InvalidOperationException();
            }
            return value;
        }
    }

    public Nullable(T value)
    {
        this.value = value;
        this.hasValue = true;
    }

    // Calling new Nullable<int>() or whatever will use the
    // implicit initialization which leaves value as default(T)
    // and hasValue as false.
}

显然,在现实code有更多的方法(如 GetValueOrDefault())和转换操作符等C#编译器增加了的取消运营商有效地代理到原来的运营商 T

Obviously in the real code there are more methods (like GetValueOrDefault()) and conversion operators etc. The C# compiler adds lifted operators which effectively proxy to the original operators for T.

目前听起来像一个破纪录的风险,这仍是一个值类型。它的的涉及拳击......,当你写的:

At the risk of sounding like a broken record, this is still a value type. It doesn't involve boxing... and when you write:

int? x = null;

这不是一个空的参考的 - 它是可空&LT的空值; INT&GT; ,即一,其中 hasVa​​lue的

that's not a null reference - it's the null value of Nullable<int>, i.e. the one where hasValue is false.

在可空类型的的盒装的CLR有一个特点,即价值得到两种盒装为空引用,或一个普通的盒装T.因此,如果你有code是这样的:

When a nullable type is boxed, the CLR has a feature whereby the value either gets boxed to a null reference, or a plain boxed T. So if you have code like this:

int? x = 5;
int y = 5;

object o1 = x;
object o2 = y;

盒装值由 01 O2 是无法区分的简称。你不能告诉大家,一个是拳击可空类型的结果。

The boxed values referred to by o1 and o2 are indistinguishable. You can't tell that one is the result of boxing a nullable type.

这篇关于? (可为空)运算符在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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