C#中的可空方法参数

重复的问题

将空参数传递给C#方法

我可以在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... } 

如果没有,我能做些类似的事吗?

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

 public void myMethod(string astring, int? anint) 

anint现在将具有HasValue属性。

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

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

你现在可以这样做:

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

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

在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... } 

并调用方法

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