Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将'null'转换为可为null的int?我总是得到0分_C#_Asp.net_.net - Fatal编程技术网

C# 如何将'null'转换为可为null的int?我总是得到0分

C# 如何将'null'转换为可为null的int?我总是得到0分,c#,asp.net,.net,C#,Asp.net,.net,出于不让您感到厌烦的原因,我有一个值为null的泛型对象,需要将其转换为可为null的int object foo = null int? bar = Convert.ToInt32(foo) // bar = 0 int? bar = (int?)Convert.ToInt32(foo) // bar = 0 int? bar = Convert.ToInt32?(foo) // not a thing 发件人: 我需要bar为null。我该如何做到这一点?以下操作将起作用 int?bar=

出于不让您感到厌烦的原因,我有一个值为
null
的泛型对象,需要将其转换为可为null的int

object foo = null
int? bar = Convert.ToInt32(foo) // bar = 0
int? bar = (int?)Convert.ToInt32(foo) // bar = 0
int? bar = Convert.ToInt32?(foo) // not a thing
发件人:


我需要
bar
null
。我该如何做到这一点?

以下操作将起作用

int?bar=(int?)foo

但是,正如注释中指出的,如果
foo
不是
null
int
的话,这将抛出一个
指定强制转换无效的异常

如果您希望仅获取一个
null
,如果转换无效,则可以使用

int?bar=foo作为int


这将隐藏转换问题。

int?bar=(int?)foo
似乎对我有用。
Convert.ToInt32()
总是返回
int
,而不是
null
。这似乎是你最初尝试的主要缺陷。如果你去一棵苹果树,你总会得到一个苹果,而不是一个橘子。我个人建议
int?bar=foo作为int
这比使用
(int?
)稍微安全一点。可能的复制比我快几秒钟。伟大的头脑都是一样的!还是傻瓜们很少有不同意见:我觉得自己很傻。试图让事情变得比他们需要的更困难,我猜,等等……:)如果foo是字符串呢?它的类型为
对象
,因此它没有义务转换为
int?
。如果
foo
不是
null
int
,肯定会出现运行时错误。。。但是所有的问题都需要将
对象null
转换为
int?空
int? bar = Expression.Constant(foo, typeof(int?)); // Can not convert System.Linq.Expression.Constant to int?