C#中的可空方法参数

时间:2009-03-12 12:16:18

标签: c# arguments nullable

重复问题

Passing null arguments to C# methods

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

如果没有,我能做些什么吗?

3 个答案:

答案 0 :(得分:19)

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

public void myMethod(string astring, int? anint)

anint现在将拥有HasValue属性。

答案 1 :(得分:14)

取决于您想要实现的目标。如果您希望能够删除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,那么,请看其他答案。 ;)

答案 2 :(得分: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...
}

并调用类似

的方法
 myMethod("Hello", 3);
 myMethod("Hello", null);