C# 中的可空方法参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/638361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:19:24  来源:igfitidea点击:

Nullable Method Arguments in C#

c#argumentsnullable

提问by

Duplicate Question

重复问题

Passing null arguments to C# methods

将空参数传递给 C# 方法

Can I do this in c# for .Net 2.0?

我可以在 c# 中为 .Net 2.0 执行此操作吗?

public void myMethod(string astring, int? anint)
{
//some code in which I may have an int to work with
//or I may not...
}

If not, is there something similar I can do?

如果没有,我可以做类似的事情吗?

采纳答案by roryf

Yes, assuming you added the chevrons deliberately and you really meant:

是的,假设您故意添加了 V 形,并且您的意思是:

public void myMethod(string astring, int? anint)

anintwill now have a HasValueproperty.

anint现在将拥有一个HasValue属性。

回答by Dead account

In C# 2.0 you can do;

在 C# 2.0 中你可以这样做;

public void myMethod(string astring, int? anint)
{
   //some code in which I may have an int to work with
   //or I may not...
}

And call the method like

并调用方法

 myMethod("Hello", 3);
 myMethod("Hello", null);

回答by Inferis

Depends on what you want to achieve. If you want to be able to drop the anintparameter, you have to create an overload:

取决于你想要达到的目标。如果您希望能够删除anint参数,则必须创建一个重载:

public void myMethod(string astring, int anint)
{
}

public void myMethod(string astring)
{
    myMethod(astring, 0); // or some other default value for anint
}

You can now do:

你现在可以这样做:

myMethod("boo"); // equivalent to myMethod("boo", 0);
myMethod("boo", 12);

If you want to pass a nullable int, well, see the other answers. ;)

如果你想传递一个可为空的 int,那么,请参阅其他答案。;)