简体   繁体   English

C#使用未分配的局部变量列表

[英]C# Use of unassigned local variable list

     public struct Mp3spelerinfo
    {
        public string ID;
        public string Make;
        public string Model;
        public string MBSize;
        public string Price;
    };                        

    //AANMAAK MP3SPELERS DMV STRUCT
    public static void maakmp3speler()
    {
        List<Mp3spelerinfo> myArray;

        Mp3spelerinfo speler1;
        speler1.ID = "1";
        speler1.Make = "GET technologies .inc";
        speler1.Model = "HF 410";
        speler1.MBSize = "4096";
        speler1.Price = "129.95";
        myArray[0] = speler1;
    }

What can I do to prefent this from happening? 我怎样做才能防止这种情况发生? What im doing is im trying to get a list so that I can use .Add to make things easier. 我在做什么是为了获取列表以便我可以使用.Add使事情变得更容易。 myArray[0] is where the error is at. myArray [0]是错误所在。

You need to actually create a new list before you do anything else: 在执行其他任何操作之前,您实际上需要创建一个新列表:

List<Mp3spelerinfo> myArray = new List<Mp3spelerinfo>();

Next, you need to add the item to the list. 接下来,您需要将该项目添加到列表中。 If you try to set the first item you'll just get an error that there aren't that many items in the list: 如果您尝试设置第一个项目,则会收到一个错误消息:列表中没有那么多项目:

myArray.Add(speler1);

You should also probably avoid calling a list myArray1 . 您还应该避免调用列表myArray1 It's not an array, it's a list. 它不是数组,而是列表。 The difference is important. 区别很重要。 It's probably better to just call it myList , assuming you don't have a more meaningful name. 假设您没有更有意义的名称,最好将其myList

I would also strongly advise you to change Mp3spelerinfo to be a class , rather than a struct . 我也强烈建议您将Mp3spelerinfo更改为class ,而不是struct It doesn't conceptually represent a single value, dealing with mutable structs is a nightmare if you're not very intimately familiar with lots of very nitty gritty details of C#. 它在概念上并不代表单个值,如果您对C#的许多非常细腻的细节不太熟悉,那么处理可变结构就是一场噩梦 You have a lot to lose, and nothing really to gain from using a struct here. 您将损失很多,在这里使用struct并没有真正的收获。 When you make that change, you'll then need to explicitly initialize speler1 using new Mp3spelerinfo(); 进行更改后,您需要使用new Mp3spelerinfo();显式初始化speler1 new Mp3spelerinfo(); to create an instance of it. 创建它的一个实例。 Classes are not implicitly initialized the way structs are. 类不是像结构那样隐式初始化的。

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

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