[英]How do I pass in nullable modifiers as out parameters in C#
Suppose I declare an int with a nullable modifier and I want to pass it as an out parameter to a function.假设我声明了一个带有可为空修饰符的 int,并且我想将它作为输出参数传递给 function。 How would I do that?
我该怎么做?
int? count = null;
if(int.TryParse(System.Console.ReadLine(), out count /* illegal */))
...
int?
is shorthand for System.Nullable<int>
.是
System.Nullable<int>
的简写。 Adding the ?
添加
?
to the end of a value type actually declares a different type of variable.值类型的末尾实际上声明了不同类型的变量。 The only reason your call to
TryParse
is invalid is because it is expecting an object of type int
, not Nullable<int>
.您对
TryParse
的调用无效的唯一原因是因为它期望 object 类型为int
,而不是Nullable<int>
。
If you are writing your own method, you can declare your argument types to be whatever you'd like, including int?
如果您正在编写自己的方法,则可以将参数类型声明为您想要的任何类型,包括
int?
. . For example:
例如:
public void SomeMethod(string input, out int? output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.