C# - How to skip parameters with default values?

2019-02-22 03:58发布

问题:

Consider the following method example:

public void MyMethod (string par1, bool par2 = "true", string par3="")
{
}

Now let's say that I call MyMethod and set par3's value to "IamString".

How could I do that without setting par2's value to true or false?

I basically want to leave par2 value to its default.

I'm asking this because in Flash's ActionScript it is possible to do that by using the keyword default so I could call MyMethod ("somestring", default, "IamString") and par2 would be interpreted as true, which is its default value. I wonder if it is possible in C# as well.

回答1:

public void MyMethod (string par1, bool par2 = "true", string par3=""){}
Myclass.MyMethod(par1:"par1", par3:"par3");

By the way, this won't work: bool par2 = "true"

string par2 = "true"

or

bool par2 = true

Talking about default values, you could also use this to get the default value for a particular type:

default(T)



回答2:

You can specify this by name the parameter:

instance.MyMethod( "Hello", par3:"bla" );

Have a look here.

And there is another bug:

bool par2 = true

is correct..