C# Default Value at Method - compile error : compile-time constant
private static Vector2 DefaultMulFactors = new Vector2(0.5f, 0.5f);
private static Point DefaultShifts = new Point(0,0);
public static Vector2 Function(Vector2? mulFactors = MyClass.DefaultMulFactors , Point? shifts = MyClass.DefaultShifts )
{
...
return result;
}
Why does my code not accept my static values? How can I assign开发者_C百科 default parameters to my function parameters? Indeed Vector2? mulFactors = new Vector(0.2,0.3)
or Vector2? mulFactors = Vector2.Zero
does not work.
You can't, basically. The value must be supported by the compiler to allow that type of usage (it is essentially a constant). I would just use null
here:
, Point? shifts = null)
then:
if(shifts == null) shifts = MyClass.DefaultShifts;
From MSDN:
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:
a constant expression;
an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
an expression of the form default(ValType), where ValType is a value type.
No one of mentioned cases is yours, that's why it doesn't work for you! :)
精彩评论