简体   繁体   English

c# 在一个类中初始化一个静态列表

[英]c# initialize a static list in a class

What I'm trying to have is a 2D global list initialized with strings.我想要的是一个用字符串初始化的二维全局列表。 If I only wanted a simple list I could just initialize the list with strings separated by a comma like this如果我只想要一个简单的列表,我可以用这样用逗号分隔的字符串初始化列表

public static readonly List<string> _architecturesName = new List<string>() {"x86","x64" }; 

I have set up a static class Globals , in this class I'm adding a List based on another class ArchitecturesClass to be used as fields for the list similar to what was done here我已经设置了一个静态类Globals ,在这个类中,我添加了一个基于另一个类ArchitecturesClass的列表,用作列表的字段,类似于这里所做的

public class ArchecturesClass
{  
    public string Id { get; set; }
    public string Name { get; set; }
}

// test1 : 
public static readonly List<ArchecturesClass> ArchitectureList =  new List<ArchecturesClass>() { "2", "9"}; 
    
// test2 : 
public static readonly List<ArchecturesClass> ArchitectureList = new List<ArchecturesClass>() 
    {
        architecturesId = "2",
        architecturesName = "3"
    };

The error on the strings is that the collection initialize has some invalid arguments and In the end, I want all classes in the project to be able to read something like Globals.ArchtecutreList.ID and a matching Globals.ArchtecutreList.Name;字符串上的错误是集合初始化有一些无效参数,最后,我希望项目中的所有类都能够读取 Globals.ArchtecutreList.ID 和匹配的Globals.ArchtecutreList.Name; and I would like to initialize this in the global class without being in a method.我想在全局类中初始化它而不是在一个方法中。

The syntax语法

new List<ArchecturesClass>() {architecturesId = "2",
                              architecturesName = "3"};

should probably be应该是

new List<ArchecturesClass>() { new ArchecturesClass>() { architecturesId = "2",
                              architecturesName = "3"}};

Collection initializers expect you to provide instances of the type contained in your list. 集合初始化器希望您提供列表中包含的类型的实例。

Your other attempt你的另一个尝试

public static readonly List<ArchecturesClass> ArchitectureList = 
       new List<ArchecturesClass>() { "2", "9"}; 

fails because "2" and "9" are strings, not instances of ArchitecturesClass .失败,因为 "2" 和 "9" 是字符串,而不是ArchitecturesClass的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM