Optional parameter in method not compile-time constant error with Rectangle

我的梦境 提交于 2019-12-08 20:14:25

问题


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.



来源:https://stackoverflow.com/questions/12146989/optional-parameter-in-method-not-compile-time-constant-error-with-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!