Question about List scope in C#
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 t开发者_运维知识库o be available globally? Perhaps I can define it elsewhere?
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
{
...
}
}
}
Yes. Define List cars at the class level, ie, outside of the private function (presuming the two functions are in the same class).
how about the oftype expression?
public void IterateThroughCars()
{
foreach (var car in _dgCars.DataSource.OfType<Car>()) // Loop through List with foreach
{
...
}
}
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.
精彩评论