C# 是否可以将列表添加到结构中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/856086/
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-05 04:21:21  来源:igfitidea点击:

is it possible to add a list to a structure?

c#listdata-structures

提问by Crash893

Is it possible to add a list to a struct?

是否可以将列表添加到结构中?

public struct test
{
    public string x;
    list<string> y = new list<string>();
}

something like that?

类似的东西?

ive been trying but im just not getting it

我一直在尝试,但我就是不明白

采纳答案by sipwiz

Yes you can have a list in struct but you cannot initialise it with a field initialiser and instead you must use the constructor.

是的,您可以在 struct 中有一个列表,但您不能使用字段初始化程序对其进行初始化,而必须使用构造函数。

struct MyStruct
{
    public List<string> MyList;
    public int MyInt;

    public MyStruct(int myInt)
    {
        MyInt = myInt;
        MyList = new List<string>();
    }
}

回答by Ali Shafai

struct can have a constructor and you can instantiate the list in the constructor.

struct 可以有一个构造函数,您可以在构造函数中实例化列表。

回答by Aditya Sehgal

I am not an expert in C# but a structure is just a prototype of how your memory would look. You will have to declare a structure variable to be able to do "new list()" and assign it to a list variable.

我不是 C# 方面的专家,但结构只是您的内存外观的原型。您必须声明一个结构变量才能执行“new list()”并将其分配给列表变量。

something like struct test a; a.y = new list();

类似于 struct test a; ay = 新列表();

I have never programmed in C# so please convert my C syntax to C#.

我从未用 C# 编程,所以请将我的 C 语法转换为 C#。

回答by sharptooth

You can do that - declare a constructor for the struct and create a list instance in the struct constructor. You can't use an initializer as you proposed in your code snippet.

您可以这样做 - 为结构声明一个构造函数并在结构构造函数中创建一个列表实例。您不能使用您在代码片段中建议的初始化程序。