C# 方法中无法识别名称
在下面的示例中,我试图通过一个方法访问我的列表,但是列表的名称无法识别,为什么C# 方法中无法识别名称,c#,C#,在下面的示例中,我试图通过一个方法访问我的列表,但是列表的名称无法识别,为什么 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<DutyDay> tour = new List<DutyDay>(); tour.Add(new DutyDay() { Day = "Day
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<DutyDay> tour = new List<DutyDay>();
tour.Add(new DutyDay() { Day = "Day 1:" });
tour.Add(new DutyDay() { Day = "Day 2:" });
tour.Add(new DutyDay() { Day = "Day 3:" });
tour.Add(new DutyDay() { Day = "Day 4:" });
tour.Add(new DutyDay() { Day = "Day 5:" });
tour.Add(new DutyDay() { Day = "Day 6:" });
listBoxDutyDays.ItemsSource = tour;
}
private void DatePicker_CalendarClosed(object sender, RoutedEventArgs e)
{
foreach (DutyDay item in tour) <-- "tour" is not recognized?!
{
}
}
}
我已经试着公开这个列表,或者把它放在其他括号中,但是译员对此并不满意
很抱歉这个愚蠢的问题,但我还是新的…您需要使Tour成为实例成员而不是局部变量,因为它在其他方法中没有作用域
public partial class MainWindow : Window
{
private List<DutyDay> tour = new List<DutyDay>();
...
进一步阅读
列表变量是在Window的构造函数中声明的,这意味着它只能在该构造函数中访问 因此,将这个变量作为全局变量,这样就可以在整个类中访问它 像
您可以阅读有关局部变量和全局变量的更多信息您只需在全局范围内声明它即可访问它 试试这个
public partial class MainWindow : Window
{
List<DutyDay> tour = new List<DutyDay>(); // it is declared as global
public MainWindow()
{
InitializeComponent();
//List<DutyDay> tour = new List<DutyDay>(); It Is declared as local
tour.Add(new DutyDay() { Day = "Day 1:" });
tour.Add(new DutyDay() { Day = "Day 2:" });
tour.Add(new DutyDay() { Day = "Day 3:" });
tour.Add(new DutyDay() { Day = "Day 4:" });
tour.Add(new DutyDay() { Day = "Day 5:" });
tour.Add(new DutyDay() { Day = "Day 6:" });
listBoxDutyDays.ItemsSource = tour;
}
private void DatePicker_CalendarClosed(object sender, RoutedEventArgs e)
{
foreach (DutyDay item in tour) <-- "tour" is not recognized?!
{
}
}
}
完美的感谢您的快速回答:-谢谢,VisualStyleElement。窗口甚至没有必要,只是将声明放在更高的位置就成功了。
public partial class MainWindow : Window
{
List<DutyDay> tour = new List<DutyDay>(); // it is declared as global
public MainWindow()
{
InitializeComponent();
//List<DutyDay> tour = new List<DutyDay>(); It Is declared as local
tour.Add(new DutyDay() { Day = "Day 1:" });
tour.Add(new DutyDay() { Day = "Day 2:" });
tour.Add(new DutyDay() { Day = "Day 3:" });
tour.Add(new DutyDay() { Day = "Day 4:" });
tour.Add(new DutyDay() { Day = "Day 5:" });
tour.Add(new DutyDay() { Day = "Day 6:" });
listBoxDutyDays.ItemsSource = tour;
}
private void DatePicker_CalendarClosed(object sender, RoutedEventArgs e)
{
foreach (DutyDay item in tour) <-- "tour" is not recognized?!
{
}
}
}