当前位置: 首页 > 工具软件 > color-compile > 使用案例 >

default parameter value for ‘color’ must be a compile-time constant

锺离烈
2023-12-01

定义了一个函数,函数有一个参数是Color类型的可选参数,想要设置其默认值为Color.Black

http://stackoverflow.com/questions/2804395/c-sharp-4-0-can-i-use-a-color-as-an-optional-parameter-with-a-default-value

I've run into this as well and the only workaround I've found is to use nullables.

public void log(String msg, Color? c = null)
{
    loggerText.ForeColor = c ?? Color.Black;
    loggerText.AppendText("\n" + msg);
}

这个解决方法中的 ??https://msdn.microsoft.com/en-us/library/ms173224.aspx

The ?? operator is called the null-coalescing operator.

It returns the left-hand operand if the operand is not null;//操作符左边不为null的时候,取左边的值

otherwise it returns the right hand operand.    //操作符左边为null的时候,取右边的值

 

http://stackoverflow.com/questions/5381717/defining-colors-as-constants-in-c-sharp

Only literals can be defined as const.

The difference is, that const values are hard-bakened into the assemblies that uses it. Should their definition change, then the call sites doesn't notice unless they get recompiled.

In contrast, readonly declares a variable in a way that it cannot be reassigned after outside theconstructor (or static constructor in case of a static readonly variable).

So, you have no other way then to use readonly here, since Color is a struct, and no primitive data type or literal.

 

转载于:https://www.cnblogs.com/chucklu/p/4884568.html

 类似资料:

相关阅读

相关文章

相关问答