简体   繁体   中英

Why doesn't Blazor support List.Add? What is the alternative?

Why cant I run the following code in a Blazor component in the @Code section:

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

This code runs fine in a console app. It won't even compile in Blazor. How do I add items to this list in Blazor? In my final solution, I need to forEach through another list of objects to get the values I need to fill the final list.

You should post more of your code.

Try this.

@code {

    List<string> dinosaurs = new List<string>();

    protected async override Task OnInitializedAsync()
    {
        dinosaurs.Add("Tyrannosaurus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");
        dinosaurs.Add("Compsognathus");
    }
}

dinasaurs is a field of your components class .

You can manipulate it from within a method.

@Brian Parker's answer shows why your code didn't compile: you can't run methods in the declarations section of your code.

If you really want to initialize those values, then try:

List<string> dinosaurs  = new List<string>
            {   "Tyrannosaurus",
                "Amargasaurus",
                "Mamenchisaurus",
                "Deinonychus",
                "Compsognathus"   };

It looks nicer anyway, right? :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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