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
Nullable Method Arguments in C#
提问by
Duplicate Question
重复问题
Passing null arguments to C# methods
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)
anint
will now have a HasValue
property.
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 anint
parameter, 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,那么,请参阅其他答案。;)