有人可以告诉我如何在其他控件和方法中使用在文本框控件中定义的变量。在标准方法中,这很好,但不确定控件。另一种方法是使其成为全局变量,但我不想这样做。代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Clean_Encoder_Box
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void goBtn_Click(object sender, EventArgs e)
{
}
private void freqValueTb_TextChanged(object sender, EventArgs e)
{
string freqValueSt = freqValueTb.Text;
ushort freqValueUs = ushort.Parse(freqValueSt);
}
}
}
答案 0 :(得分:1)
在方法(即本地)中声明的变量仅在此方法中可见。在类级别上声明字段。
public partial class Form1 : Form
{
private string _freqValueSt;
private ushort _freqValueUs;
public Form1()
{
InitializeComponent();
}
private void goBtn_Click(object sender, EventArgs e)
{
// _freqValueSt and _freqValueUs are visible here.
}
private void freqValueTb_TextChanged(object sender, EventArgs e)
{
_freqValueSt = freqValueTb.Text;
_freqValueUs = ushort.Parse(freqValueSt);
}
}
或创建一个属性
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void goBtn_Click(object sender, EventArgs e)
{
ushort f = Frequency;
}
private ushort Frequency => ushort.Parse(freqValueTb.Text);
}
或者使用安全的变体
private ushort? Frequency {
get {
if (ushort.TryParse(freqValueTb.Text, out ushort f)) {
return f;
}
return null;
}
}