简体   繁体   English

如何在 C# 中将可空修饰符作为输出参数传递

[英]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.

相关问题 C# 如何将可选参数作为集合传递? - C# how do I pass optional parameters as a collection? 如何将两个参数传递给 c# 中的 GraphQLHttpClient? - How do I pass two parameters to GraphQLHttpClient in c#? C#-是否必须将参数添加到参数集合中 - C# -Do I have to add out parameter to parameters collection 可空类型在 C# 中如何工作? - How do nullable types work in C#? 如何在c#,winforms的运行时编译中传递参数? - How do I pass parameters in run-time compilation in c#, winforms? 将方法附加到C#中的事件时如何传递参数 - how do I pass parameters when attaching a method to an event in c# 如何将两个相似的具体对象传递给具有在C#中实现泛型的接口参数的方法? - How do I pass two similar concrete objects to a method with interface parameters that implement generics in C#? 如何从浏览器 URL 向 c# 方法传递多个参数 - How do i pass multiple parameters to c# method from browser URL 如何从ac#客户端将多个参数传递给WCF Restful服务? - How do I pass multiple parameters to a WCF Restful service from a c# client? 如何在C#/ Visual Studio 2010中将自定义SQL字符串或参数传递给tableadapter或诸如此类? - How do I pass a custom SQL string or parameters to a tableadapter or somesuch in C# / Visual Studio 2010?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM