4

I have a method:

public void MyMethod(string myParam1,string myParam2="")
{
     myParam2 = (myParam2 == "")?myParam1:myParam2;
}

Is there any way to do this something like:

public void MyMethod(string myParam1,string myParam2 = (myParam2 == "")?myParam1:myParam2)
4

4 回答 4

6

No.

The default value of parameters needs to be known at compile time. The first snippet you provided is the correct way to do this. Or as has been pointed out by other answers, provide an overload method that only accepts a single parameter.

于 2013-02-28T15:15:43.540 回答
3

In order to perform what you want you'll need to use an overload instead of an optional parameter.

于 2013-02-28T15:16:11.493 回答
2

There is no chance I believe what you tried to.

If you want to do process like this, best options looks like method overloading.

Overload resolution is a compile-time mechanism for selecting the best function member to invoke given an argument list and a set of candidate function members.

于 2013-02-28T15:18:37.500 回答
2

Not directly, as the default value must be known at compile time. The first method you describe is the correct way to do this.

However, you could do:

  1. Set a default of null and coalesce it as you use it:

    public void MyMethod(string myParam1, string myParam2 = null)
    {
        Console.WriteLine(myParam2 ?? myParam1);
    }
    
  2. Use overloading:

    public void MyMethod(string myParam1, string myParam2)
    {
        Console.WriteLine(myParam2);
    }
    
    public void MyMethod(string myParam1)
    {
        MyMethod(myParam1, myParam1);
    }
    
于 2013-02-28T15:20:27.137 回答