如何在 C# 中将 Null 值赋给 Non-Nullable 类型变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15491889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:59:14  来源:igfitidea点击:

How to assign Null value to Non-Nullable type variable in C#?

c#

提问by MSU

Such as i have declared,

如我所声明的,

double x;

双 x;

now i want to assign

现在我想分配

x=NULL how can i do this ? I have seen some other answers of it but couldn't understand them, that's why opening this thread .

x=NULL 我该怎么做?我已经看到了其他一些答案,但无法理解它们,这就是打开此线程的原因。

回答by TGH

You have to declare it as a nullable type:

您必须将其声明为可空类型:

double? x;
x = null;

Non nullable types like double can not be null

不可为空的类型,如 double 不能为空

回答by Andrew Cooper

Short answer: You can't.

简短的回答:你不能。

A doublecan only contain a valid double-precision floating point value.

Adouble只能包含有效的双精度浮点值。

回答by Rahul

use 
double? x;

and assign null value to x variable like

并将空值分配给 x 变量,如

x = null;

回答by sa_ddam213

You cant assign null to a non-nullable type

您不能将 null 分配给不可为 null 的类型

You can use NaN(not a number) for a non-nullable double

您可以将NaN(不是数字)用于不可为空的double

double x;
x = double.NaN;

回答by internals-in

Nullable types are instances of the System.Nullable(Of T) struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

可空类型是 System.Nullable(Of T) 结构的实例。可空类型可以表示其基础值类型的正确值范围,外加一个额外的空值。例如,一个 Nullable,发音为“Nullable of Int32”,可以分配从 -2147483648 到 2147483647 的任何值,或者可以分配空值。可以为 Nullable 分配值 true false 或 null。当您处理包含可能未分配值的元素的数据库和其他数据类型时,将 null 分配给数字和布尔类型的能力特别有用。例如,数据库中的布尔字段可以存储值 true 或 false,也可以未定义。

double? amount = null;

http://msdn.microsoft.com/en-us/library/vstudio/2cf62fcy.aspx

双倍的?金额 = 空;

http://msdn.microsoft.com/en-us/library/vstudio/2cf62fcy.aspx

Possible Duplicates:

可能的重复:

Why can't I set a nullable int to null in a ternary if statement?
Nullable types and the ternary operator: why is `? 10 : null` forbidden?

为什么我不能在三元 if 语句中将可为 null 的 int 设置为 null?
可空类型和三元运算符:为什么是`?10 : null` 被禁止?