c# - 如何从应该返回整数的函数返回 null
问题描述
在一次采访中,有人问我如何从整数、双精度类型等的方法中返回 Null,而无需任何输出参数。
解决方案
你可以做这样的事情。
您必须首先使int
类型可为空。通过int?
正常使用int
c# 中的数据类型默认情况下不可为空,因此您必须将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;
}
推荐阅读
- http - HTTP Keep Alive 会减少 TLS 连接吗?
- aws-lambda - 从 Lambda 内部运行 databrew.describe_job_run() 不起作用
- rundeck - 按时间限制重试,而不是尝试
- javascript - 在 react.js 中使用按钮同时发送表单和 href
- html - 如何在卡片中插入行/列(使用 v-for)?
- terminal - 终端在 JupyterLab Launcher 中不可用
- c++ - 关于 Sentinel 循环 C++ 的建议
- java - 同一个包中的两个类不能一起工作
- python - .aspx 网站网页抓取使用 python
- reactjs - How do I render the following code in the render function?