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

本文介绍如何在C#中定义一个接受Color类型可选参数的函数,并设置其默认值为Color.Black。通过使用空合并运算符(??)来实现这一目标,同时讨论了const与readonly的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值