How to create structure with null value support?

做~自己de王妃 提交于 2020-01-23 04:45:18

问题


I'm new in C#. In c# I can't set value of a structure to null how can I create a structure with null value support?


回答1:


Structs and value types can be made nullable by using the Generic Nullable<> class to wrap it. For instance:

Nullable<int> num1 = null;

C# provides a language feature for this by adding a question mark after the type:

int? num1 = null;

Same should work for any value type including structs.

MSDN Explanation: Nullable Types (c#)




回答2:


You can use Nullable<T> which has an alias in C#. Keep in mind that the struct itself is not really null (The compiler treats the null differently behind the scenes). It is more of an Option type.

Struct? value = null;

As @CodeInChaos mentions Nullable<T> is only boxed when it is in a non-null state.

Nullable Types

Boxing Nullable Types




回答3:


you can use Nullable<T> for structs, or the shorthand form (?) of the same:

Represents an object whose underlying type is a value type that can also be assigned null like a reference type.

struct Foo
{
}

Nullable<Foo> foo2 = null; 
Foo? foo = null; //equivalent shorthand form



回答4:


Since the "Struct" is not a reference type, you cannot assign "null" as usual manner. so you need to use following form to make it "nullable"

[Struct Name]? [Variable Name] = null

eg.

Color? color = null;

then you can assign null for the object and also check the nullability using conditional statements.



来源:https://stackoverflow.com/questions/6564682/how-to-create-structure-with-null-value-support

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