C#中的可空方法参数

13 c# arguments nullable

重复的问题

将空参数传递给C#方法

我可以在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...
}
Run Code Online (Sandbox Code Playgroud)

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

ror*_*ryf 22

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

public void myMethod(string astring, int? anint)
Run Code Online (Sandbox Code Playgroud)

anint现在将拥有一处HasValue房产.


Inf*_*ris 16

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

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

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

你现在可以这样做:

myMethod("boo"); // equivalent to myMethod("boo", 0);
myMethod("boo", 12);
Run Code Online (Sandbox Code Playgroud)

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

  • 那不是多态性 (3认同)
  • 我认为你可以通过如下定义来避免重载:`public void myMethod(string astring,int?anint = null)`.这样,只能使用字符串作为参数调用方法,并且anint变量的值将为null; 并用字符串和整数调用它. (2认同)

Dea*_*unt 8

在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...
}
Run Code Online (Sandbox Code Playgroud)

并调用方法

 myMethod("Hello", 3);
 myMethod("Hello", null);
Run Code Online (Sandbox Code Playgroud)