c# - 在 C# Windows 窗体中将用户输入保存为变量

标签 c# variables folderbrowserdialog

到目前为止,如果用户输入某些内容,我会存储在标签属性中。我知道这不对。如何根据用户输入更新变量,以便在需要使用它的任何事件中使用?

这是我尝试过的许多事情之一。我什至无法找出正确的搜索词来用谷歌搜索我需要做的事情的解决方案。

namespace Words
{
  public partial class formWords : Form
  {
    int x = 5;
    int y = 50;
    int buttonWidth = 120;
    int buttonHeight = 40;
    string fileList = "";
    string word = "";
    string wordFolderPath = @"C:\words\";// this is the variable I want to change with the dialog box below.

  private void selectWordFolderToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog folder = new FolderBrowserDialog();
        if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string folderPath = folder.SelectedPath;
            formWords.wordFolderPath = folderPath;
        }
    }

最佳答案

wordFolderPath 是一个对您的类(class)公开的变量(但在类(class)之外是私有(private)的)。这意味着您的类中的任何内容都可以自由读取/写入该值。

至于你的语法,你可以只使用变量名或使用this.:

private void DoAThing()
{
    wordFolderPath = "asdf";
    this.wordFolderPath = "qwerty"; //these are the same
}

访问内部变量时不能使用当前类的名称。 formWords 是一种类型,而不是实例。

使用 this 的唯一好处是在方法中定义同名变量是合法的。使用此关键字可确保您谈论的是类(class)的成员。

关于c# - 在 C# Windows 窗体中将用户输入保存为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17626445/

相关文章:

c# - 在可移动设备/可移动存储上使用 FolderBrowserDialog

c# - FolderBrowserDialog 嵌套文件夹

c# - 如何检查字符串是否包含带通配符的子字符串?像 abc*xyz

java - 子类和父类(super class)中的同名变量

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c# - 为什么 FolderBrowserDialog 对话框不滚动到选定的文件夹?

c# - 如何在 C# 中使用相对路径实例化新的 ChromeDriver?

c# - PresentationFramework.dll 中出现“System.Reflection.TargetInvocationException”

c# - 如何使用 Bing API 通过 Bing map 搜索特定商店

c++ - 公共(public)变量