Variable type ending with ?

非 Y 不嫁゛ 提交于 2019-12-17 16:35:39

问题


What does ? mean:

public bool? Verbose { get; set; }

When applied to string?, there is an error:

The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'


回答1:


? makes your non-nullable (value) types nullable. It doesn't work for string, as it is reference type and therefore nullable by default.

From MSDN, about value types:

Unlike reference types, a value type cannot contain the null value. However, the nullable types feature does allow for values types to be assigned to null.

? is basically a shorthand for Nullable<T> structure.

If you want to know more, MSDN has a great article regarding this topic.




回答2:


The ? is shorthand for the struct below:

struct Nullable<T>
{
    public bool HasValue;
    public T Value;
}

You can use this struct directly, but the ? is the shortcut syntax to make the resulting code much cleaner. Rather than typing:

Nullable<int> x = new Nullable<int>(125);

Instead, you can write:

int? x = 125;

This doesn't work with string, as a string is a Reference type and not a Value type.




回答3:


bool? is a short form for System.Nullable<bool>. Only value types are accepted for the type parameter and not reference types (like e.g. string).




回答4:


bool? is a shorthand notation for Nullable<bool>. In general, the documentation states:

The syntax T? is shorthand for Nullable, where T is a value type. The two forms are interchangeable

Since string is not a value type (it's a reference type), you cannot use it as the generic parameter to Nullable<T>.




回答5:


The ? operator indicates that the property is in fact a nullable type.

public bool? Verbose { get; set; } 

is equilvalent to

public Nullable<bool> Verbose { get; set; }

A nullable type is a special type introduced in c# 2.0 which accepts a value type as a generic praramater type and allow nulls to be assigned to the type.

The nullable type only accept value types as generic arguments which is why you get a compile error when you try to use the ? operator in conjunction with the string type.

For more information: MSDN Nullable Types




回答6:


Only value types can be declared as Nullable. Reference types are bydefault nullable. So you cannot make nullable string since string is a reference type.




回答7:


the ? means that your value type can have a null value, specially in the case of database

handling you need these nullables to check if some value is null or not.

It can be applied to only value types coz reference types can be null .



来源:https://stackoverflow.com/questions/2863963/variable-type-ending-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!