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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19393481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:53:40  来源:igfitidea点击:

c# initialize a static list in a class

c#

提问by Wolfkc

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

我想要的是一个用字符串初始化的 2D 全局列表。如果我只想要一个简单的列表,我可以用这样的逗号分隔的字符串初始化列表

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

I have setup 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: Are 2 dimensional Lists possible in c#?

我已经设置了一个静态类“Globals”,在这个类中,我添加了一个基于另一个类“ArchitecturesClass”的列表,用作列表的字段,类似于这里所做的:Are 2 dimensional Lists possible in c#?

 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 in valid 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;and I would like to initialize this in the global class without being in a method.

字符串上的错误是集合初始化有一些有效参数,最后我希望项目中的所有类都能够读取类似 Globals.ArchtecutreList.ID 和匹配的内容Globals.ArchtecutreList.Name;,我想在没有在方法中的全局类。

采纳答案by Eric J.

The syntax

语法

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

should probably be

应该是

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

Collection initializersexpect 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.