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

定义了一个函数,函数有一个参数是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.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(784)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示