C#,Java中的null是什么? [英] What is null in c#, java?

查看:99
本文介绍了C#,Java中的null是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像...在C ++中是 0 吗?还是某个特殊对象?或者也许完全不同?

Like... is it 0 like in C++? Or is it some "special" object? Or maybe something totally different?

-编辑-

我确实知道这是什么,问题是-如何完成

推荐答案

关于实现细节而不是语义,答案是特定于给定实现的。

Since you're asking about implementation details, rather than semantics, the answer is specific to a given implementation.

在C#中,空可以是三件事。引用,指针和可为空的类型。

There are three things in C# that "null" can be. A reference, a pointer, and a nullable type.

CLR上C#的实现通过零位表示空的引用。 (其中位数是要运行的CLR特定版本上的托管指针的适当大小。)

The implementation of C# on the CLR represents a null reference by zero bits. (Where the number of bits is the appropriate size to be a managed pointer on the particular version of the CLR that you're running.)

毫无疑问,空值 pointer 以相同的方式表示。您可以通过创建一个不安全的块,创建一个指向void的空指针,然后将其转换为IntPtr,然后将IntPtr转换为int(或在64位系统上为long)来证明这一点。果然,您将得到零。

Unsurprisingly, a null pointer is represented the same way. You can demonstrate this in C# by making an unsafe block, making a null pointer to void, and then converting that to IntPtr, and then converting the IntPtr to int (or long, on 64 bit systems). Sure enough, you'll get zero.

空的可空值类型也是由零实现的,尽管方式不同。当你说

A null nullable value type is also implemented by zeroes, though in a different way. When you say

int? j = null;

int? j = null;

我们实际创建的东西在道德上等同于:

what we actually create is the moral equivalent of:

struct NullableInt 
{
    int value;
    bool hasValue;
}

具有适当的访问器方法,依此类推。当这些东西之一分配为空时,我们只用零位填充整个东西。该值为整数零,并且hasValue用零填充,因此变为false;将hasValue字段设置为false的可为null的类型被视为null。

With appropriate accessor methods, and so on. When one of those things is assigned null, we just fill the whole thing with zero bits. The value is the integer zero, and the hasValue is filled with zeroes and therefore becomes false; a nullable type with the hasValue field set to false is considered to be null.

我不知道C#/ CLI其他实现的实现细节。如果它们不同,我会感到惊讶。这是实现null的显而易见且明智的方法。但是,如果您对具体的实施细节有疑问,则必须询问知道您感兴趣的实施情况的人。

I do not know what the implementation details are on other implementations of C# / the CLI. I would be surprised if they were different; this is the obvious and sensible way to implement nulls. But if you have questions about a specific implementation detail, you'll have to ask someone who knows about the implementation you're interested in.

这篇关于C#,Java中的null是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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