有关C#中的列表范围的问题 [英] Question about List scope in C#

查看:55
本文介绍了有关C#中的列表范围的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个私有函数Load,它创建一个列表,创建多个对象,然后将一个数据网格绑定到该列表.代码类似于:

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?

推荐答案

嗯,这与列表无关.它是一般变量范围.您尚未显示声明cars变量的位置或尝试使用它的位置-但我猜是您已将其设置为局部变量,并且这两个代码段使用不同的方法.

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.

您可能希望将其设置为 instance 变量.例如:

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
        {
            ...
        }
    }
}

这篇关于有关C#中的列表范围的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆