Nullable Method Arguments in C# [duplicate]

不想你离开。 提交于 2019-12-21 07:14:19

问题


Duplicate Question

Passing null arguments to C# methods

Can I do this in c# for .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?


回答1:


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

public void myMethod(string astring, int? anint)

anint will now have a HasValue property.




回答2:


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

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. ;)




回答3:


In C# 2.0 you can do;

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);


来源:https://stackoverflow.com/questions/638361/nullable-method-arguments-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!