Skip to main content
 首页 » 编程设计

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

2024年02月05日11dyllove98

我是 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 的回答的评论,以讨论一般情况下的缺点。