如何从应该返回整数的函数中返回 null

Har*_*sir 2 c#

我在一次采访中被问到如何在没有任何输出参数的情况下从具有整数、双精度类型等的方法中返回 Null。

Reh*_*hah 6

你可以做这样的事情。

您必须首先使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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 这里还有其他人试图点击“自己尝试”吗? (2认同)