相关疑难解决方法(0)

Nullable <int>与int? - 有什么区别吗?

显然,Nullable<int>int?在数值上相等.有没有理由选择其中一个?

Nullable<int> a = null;
int? b = null;
a == b; // this is true
Run Code Online (Sandbox Code Playgroud)

.net c#

85
推荐指数
4
解决办法
3万
查看次数

Nullable <T>的装箱/拆箱行为怎么可能?

我今天早些时候发生的事情让我摸不着头脑.

Nullable<T>可以为任何类型的变量赋值null.例如:

int? i = null;
Run Code Online (Sandbox Code Playgroud)

起初,我看不出如何做到这一点是可能的,而不以某种方式从定义的隐式转换objectNullable<T>:

public static implicit operator Nullable<T>(object box);
Run Code Online (Sandbox Code Playgroud)

但是上面的运算符显然不存在,就好像它确实如此,那么下面的内容也必须是合法的,至少在编译时(它不是):

int? i = new object();
Run Code Online (Sandbox Code Playgroud)

然后我意识到,也许Nullable<T>类型可以定义一个隐式转换为一些永远无法实例化的任意引用类型,如下所示:

public abstract class DummyBox
{
    private DummyBox()
    { }
}

public struct Nullable<T> where T : struct
{
    public static implicit operator Nullable<T>(DummyBox box)
    {
        if (box == null)
        {
            return new Nullable<T>();
        }

        // This should never be possible, as a DummyBox cannot be instantiated.
        throw new InvalidCastException();
    }
} …
Run Code Online (Sandbox Code Playgroud)

.net c# vb.net boxing nullable

32
推荐指数
1
解决办法
5078
查看次数

标签 统计

.net ×2

c# ×2

boxing ×1

nullable ×1

vb.net ×1