【问题标题】:C# - variable reference does not exist in the current contextC# - 当前上下文中不存在变量引用
【发布时间】:2016-05-31 10:55:24
【问题描述】:

我在主窗口类中有这段代码,我在其中声明了一些值以放入ListForTesting 列表中,并使测试出现在组合框中。稍后有另一个组合框取决于第一个组合框,我在下面向您展示代码:

值得一提的是,我对 C# 完全陌生。仅在 VBA 中编码。我是一名机械工程师,不是软件 :)

主窗口代码

public MainWindow()
{
    InitializeComponent();
    grid_projectConfig.Visibility = Visibility.Collapsed;
    grid_projectOverview.Visibility = Visibility.Collapsed;
    grid_test.Visibility = Visibility.Collapsed;
    grid_reports.Visibility = Visibility.Collapsed;

    //ListForTesting holds the hardcoded set of tests and manoeuvres
    List<HelpClass.TestID> ListForTesting = new List<HelpClass.TestID>();

    //TestObject holds the test name, ID and all the manoeuvres related to it
    HelpClass.TestID TestObject = new HelpClass.TestID();
    TestObject.testName = "Steady State";
    TestObject.ID = 0;
    //Manoeuvre holds the manoeuvre name and its ID
    TestObject.Manoeuvres = new List<HelpClass.ManoeuvresID>();
    HelpClass.ManoeuvresID Manoeuvre = new HelpClass.ManoeuvresID();
    Manoeuvre.manName = "30 kph";
    Manoeuvre.manID = 0;
    //add the Manoeuvre to the TestObject
    TestObject.Manoeuvres.Add(Manoeuvre);
    //create new Manoeuvre
    Manoeuvre = new HelpClass.ManoeuvresID();
    Manoeuvre.manName = "50 kph";
    Manoeuvre.manID = 1;
    TestObject.Manoeuvres.Add(Manoeuvre);
    //add the TestObject to the ListForTesting
    ListForTesting.Add(TestObject);


    //display the tests in a combobox
    combobox_testType.ItemsSource = ListForTesting.Select(t => t.testName);
}

第二个组合框代码

public void combobox_testType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    combobox_testType.ItemsSource = ListForTesting[1].Manoeuvres.Select(t => t.manName);
}

最后一行代码不起作用,因为它告诉我它在当前上下文中不存在。

【问题讨论】:

  • 有什么问题?

标签: c# list combobox


【解决方案1】:

问题是变量ListForTestingscope:通过在MainWindow 构造函数中声明它,可以限制它对该方法的可见性。

允许从类中的另一个方法访问ListForTesting(即:combobox_testType_SelectionChanged),您必须将其声明为类级变量,如下所示:

public class MainWindow : Window
{
    private List<HelpClass.TestID> ListForTesting; // Variable declaration

    public MainWindow()
    {
        // code

        ListForTesting = new List<HelpClass.TestID>(); // Initialization

        // code
    }
}

【讨论】:

    【解决方案2】:

    变量ListForTesting 在构造函数的范围内。您需要将变量移出那里才能在类的其他地方访问它。

    List<HelpClass.TestID> ListForTesting;
    
    public MainWindow()
    {
    ...
       ListForTesting = new List<HelpClass.TestID>();
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多