Optional parameter in method not compile-time cons

2019-06-20 05:59发布

问题:

I have a method where I'd like to use a Rectangle optional parameter with default value of (1,1,1,1).

void Method(int i, int j = 1, Rectangle rect = new Rectangle(1,1,1,1)) {} //error

How do I resolve this? (I'm using XNA, so it's a Microsoft.Xna.Framework.Rectangle.)

回答1:

You don't. optional parameters must be compile time constants, and new Rectangle(1,1,1,1) isn't a compile time constant.

You could have two method overloads, one that doesn't have a rectangle:

void Method(int i, int j = 1) 
{
    Method(i, j, new Rectangle(1,1,1,1)) 
}


回答2:

I just found a better way:

void MyMethod(string someString, Rectangle rect = default(Rectangle))
{
    if (rect == default(Rectangle)) 
        rect = new Rectangle(1, 1, 1, 1);
}

There may only be one problem: when the default and passed values match, it will still be true for == default(T). But one workaround is to pass null and check for that to set it to default value ot type.