首页 > 解决方案 > 如何从应该返回整数的函数返回 null

问题描述

在一次采访中,有人问我如何从整数、双精度类型等的方法中返回 Null,而无需任何输出参数。

标签: c#

解决方案


你可以做这样的事情。

您必须首先使int类型可为空。通过int? 正常使用intc# 中的数据类型默认情况下不可为空,因此您必须将int //not nullable类型显式转换为int? //nullable

你可以用 double 等做同样的事情。

// the return-type is int?. So you can return 'null' value from it.
public static int? method() 
{
   return null;
}

也可以这样写上面的方法:

// this is another way to convert "non-nullable int" to "nullable int".
public static Nullable<int> method()
{
   return null;
}

推荐阅读