简体   繁体   English

C#中的可空类型

[英]nullable types in c#

I am a java beginner and I have to compare null values in java with null in C# . 我是java初学者,我必须将Java中的null值与C# null进行比较。

I read that java does not assume anything to be null and always allocates memory but c# on the contrary assumes all to be null??? 我读到java不会假设任何东西都为空,并且总是分配内存,但是相反,c#假定所有东西都为空? (did not understand what does this mean) (不明白这是什么意思)

I also read that ordinary types in c# cannot be null but then i saw a code which says : 我还读到c#中的普通类型不能为null,但是随后我看到一个代码,内容为:

int? a = null;

int is ordinary type right? int是普通类型吧?

I am really getting confused , can anybody help me out? 我真的很困惑,有人可以帮我吗?

Thanks in advance 提前致谢

int is a primitive struct, yes. int是原始结构,是的。 However, 然而,

int?

is syntactic sugar for 是语法糖

Nullable<int>

which is a completely different type. 这是完全不同的类型。

See: http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx 请参阅: http : //msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

Take a look at this MSDN article : 看一下这篇MSDN文章

Nullable types are instances of the System.Nullable struct. 可空类型是System.Nullable结构的实例。 A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. 可空类型可以表示其基础值类型的正确值范围,以及附加的空值。

class NullableExample
{
    static void Main()
    {
        int? num = null;

        // Is the HasValue property true? 
        if (num.HasValue)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        // y is set to zero 
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false 
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}

null is pretty similar in C# and Java. null在C#和Java中非常相似。 C#'s struct s cannot be null, with the exception of Nullable<T> (which is itself a struct , but through some compiler magic can pretend to have a null value). C#的struct不能为null,但Nullable<T>除外(后者本身是struct ,但是通过一些编译器魔术可以假装具有null值)。 Java's primitives cannot be null. Java的原语不能为null。

int? is shorthand for Nullable<int> . Nullable<int>简写。 See Nullable Types for more info on that. 有关更多信息,请参见可空类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM