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

标签 c# constructor instantiation

我是 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/

相关文章:

java构造函数顺序

java - 实例化泛型类的 JAVA 数组

python - 如果我将类的第二个实例归因于包含现有实例的相同变量,会发生什么情况?

c# - Unity - 在游戏对象实例化后重绘/重绘场景

c# - 使用异步 lambda 的并行 foreach

c# - GridView RowUpdating 在 PostBack 后返回旧值

c# - 设置类属性的问题

c++ - 在构造函数中初始化引用

c++ - 如何(重新)调用初始化对象的构造函数?

c# - "Update-Database"命令失败并出现 TimeOut 异常