gpt4 book ai didi

c# - 实例化:将列表移动到参数中

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:49 24 4
gpt4 key购买 nike

我是 C# 的新手,一直在努力寻找一种惯用的方法来在构造函数中初始化列表。

没有完全解决问题的相关问题:

这可行,但有一个缺陷:

class Datapoint
{
public bool Debug { get; set; }
public string Pattern { get; private set; }

// I would prefer to initialize this list in the constructor
public List<Dictionary<string, dynamic>> operations =
new List<Dictionary<string, dynamic>>();

// constructor
public Datapoint(bool debug = false,
string pattern = ""
// I would prefer operations to go here
// but the following doesn't work:
// List<Dictionary<string, dynamic>> operations =
// new List<Dictionary<string, dynamic>>()
)
{
Debug = debug;
Pattern = pattern;
}
}


// Let's define some Datapoints
class Definitions
{
public static Datapoint turtles = new Datapoint
(
pattern: @"turtle pattern",
// I would prefer operations to go here
)
{
operations =
{ new Dictionary<string, dynamic>
{
["func"] = "stitch_lines"
}
}
};
}

缺陷是我不能将操作设置为私有(private),否则在创建海龟时会出错。

理想情况下,我希望 operations 成为构造函数的参数,但我遗漏了一些东西,因为我尝试的每个组合都会产生此错误:

Default parameter value for operations must be a compile-time constant.

提前感谢您的任何见解。

最佳答案

您可以接收一个null,然后在您的构造函数中检查它:

public Datapoint(
bool debug = false,
string pattern = "",
List<Dictionary<string, dynamic>> operations = null
)
{
Debug = debug;
Pattern = pattern;
this.operations = operations ?? new List<Dictionary<string, dynamic>>();
}

但是,请参阅 D Stanley 的回答的评论,以讨论一般情况下的缺点。

关于c# - 实例化:将列表移动到参数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33640995/

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