gpt4 book ai didi

c# - 默认参数值必须是编译时常量错误消息

转载 作者:行者123 更新时间:2023-12-02 11:07:25 26 4
gpt4 key购买 nike

我似乎收到一条错误消息,如标题中提到的那样。
“'randomizer'的默认参数值必须是编译时常量错误消息。”

对于此代码:

    public Random Randomizer {
get;
private set;
}
public ShuffleDeck( Random randomizer = new Random(DateTime.Now.Millisecond)) {
this.Randomizer = randomizer;
}

我不知道为什么吗?有人有任何线索吗?

最佳答案

and I cant figure out why?



嗯,这就是该语言的 documentation所说的。

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.


您可以做(但请参见 Servy's comment):
public ShuffleDeck(Random randomizer = null) {
if (randomizer == null)
this.Randomizer = new Random(DateTime.Now.Millisecond);
else
this.Randomizer = randomizer;
//or this.Randomizer = randomizer ?? new Random());
}

或者,您可以具有如下重载构造函数:
public ShuffleDeck()
: this(new Random(DateTime.Now.Millisecond))
{
}
public ShuffleDeck(Random randomizer)
{
this.Randomizer = randomizer;
}

关于c# - 默认参数值必须是编译时常量错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22969857/

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