gpt4 book ai didi

c# - 使用 System.Drawing.Color 类型的可选参数

转载 作者:可可西里 更新时间:2023-11-01 03:07:10 24 4
gpt4 key购买 nike

我开始利用 .Net 4.0 中的可选参数

我遇到的问题是当我尝试声明 System.Drawing.Color 的可选参数时:

public myObject(int foo, string bar, Color rgb = Color.Transparent)
{
// ....
}

我希望 Color.Transparent 成为 rgb 参数的默认值。问题是,我一直收到这个编译错误:

Default parameter value for 'rgb' must be a compile-time constant

如果我只能将原始类型用于可选参数,那真的会扼杀我的计划。

最佳答案

在这种情况下,可以使用可空值类型来提供帮助。

public class MyObject 
{
public Color Rgb { get; private set; }

public MyObject(int foo, string bar, Color? rgb = null)
{
this.Rgb = rgb ?? Color.Transparent;
// ....
}
}

顺便说一句,这是必需的,因为默认值是在编译期间在调用点填充的,而 static readonly 值直到运行时才设置。 (通过类型初始化器)

关于c# - 使用 System.Drawing.Color 类型的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3420678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com