c# - 如何从应返回整数的函数中返回 null

标签 c#

我在一次采访中被问及如何从具有整数、 double 类型等的方法返回 Null,而没有任何输出参数。

最佳答案

你可以这样做。

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

你可以用 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;
}

关于c# - 如何从应返回整数的函数中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53852117/

相关文章:

c# - 使用 log4net 在运行时读取并记录 HttpSession 数据

c# - 如何保留 Db Context 和 Restore 的更改跟踪信息?

c# - 我的页面不会显示我的多 View View

c# 对静态函数的泛型方法调用

c# - 为什么 string.StartsWith ("\u2D2D") 总是返回 true?

c# - Naudio,如何判断播放完成

c# - 从 c#.. 中的字符串中删除 2 个或更多空格?

c# - 使用 xamarin (ios) 扫描本地网络中的设备

c# - 隐式运行单元测试

c# - 以编程方式自动化 Web 登录