Question about List scope in C#

别等时光非礼了梦想. 提交于 2019-12-11 19:39:08

问题


I have a private function Load which creates a list, creates several objects and then binds a datagrid to the list. The code is similar to:

List<Car> cars = new List<Car>();
cars.Add(new Car("Ford", "Mustang", 1967));
cars.Add(new Car("Shelby AC", "Cobra", 1965));
cars.Add(new Car("Chevrolet", "Corvette Sting Ray", 1965));
_dgCars.DataSource = cars;

Now I would like to loop through the values in another private function. I tried something similar to:

foreach (Car car in cars) // Loop through List with foreach
{
     // Need to access individual object properties here
}

I am getting an error that cars does not exist in the current context. Is there a change I can make that will allow the List to be available globally? Perhaps I can define it elsewhere?


回答1:


Well, this is nothing to do with lists as such. It's general variable scope. You haven't shown where you've declared the cars variable or where you're trying to use it - but my guess is that you've made it a local variable, and the two snippets of code are in different methods.

You possibly want to make it an instance variable. For example:

public class Test
{
    private List<Car> cars;

    public void PopulateDataSource()
    {
        cars = new List<Car>
        {
            new Car("Ford", "Mustang", 1967),
            new Car("Shelby AC", "Cobra", 1965),
            new Car("Chevrolet", "Corvette Sting Ray", 1965)
        };
        _dgCars.DataSource = cars;
    }

    public void IterateThroughCars()
    {
        foreach (Car car in cars) // Loop through List with foreach
        {
            ...
        }
    }
}



回答2:


Yes. Define List cars at the class level, ie, outside of the private function (presuming the two functions are in the same class).




回答3:


how about the oftype expression?

public void IterateThroughCars()
{
    foreach (var car in _dgCars.DataSource.OfType<Car>()) // Loop through List with foreach
    {
        ...
    }
}



回答4:


The foreach loop does not work with list because the list does not contain .Length property. If you want to iterate through list plz use for loop or while loop like below

for(int i=0;i<cars.Count;i++)
{
  Car objCar=cars[i];
}

I hope it will solve your problem.



来源:https://stackoverflow.com/questions/4280695/question-about-list-scope-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!