我正在创建垃圾邮件检查程序。一种方法扫描电子邮件,另一种方法为一组单词和短语添加一个已知标志以进行检查;这两种方法都是Tester
类的一部分。目前,每个方法都有一个按钮,但每个事件都会创建自己的垃圾邮件对象。如何让两个事件都使用相同的对象,允许扫描识别我刚刚添加的标志?
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 HW8_DR
{
public partial class Spam_Scanner : Form
{
public Spam_Scanner()
{
InitializeComponent();
}
private void testButton_Click(object sender, EventArgs e)
{
Tester scan = new Tester();
scan.tester(Convert.ToString(emailBox.Text));
this.SpamRatingBox.Text = string.Format("{0:N1}%", Tester.countSpam / Tester.wordCount * 100);
this.WordsBox.Text = Tester.posSpam;
this.OutputPanal.Visible = true;
this.pictureBox1.Visible = false;
}
private void addButton_Click(object sender, EventArgs e)
{
Tester scan = new Tester();
scan.addSpam(Convert.ToString(addFlagBox.Text));
this.addFlagBox.Text = "";
}
}
}
答案 0 :(得分:2)
将Tester
变量移动到类字段,如下所示:
public partial class Spam_Scanner : Form
{
Tester scan;
public Spam_Scanner()
{
InitializeComponent();
scan = new Tester();
}
private void testButton_Click(object sender, EventArgs e)
{
scan.tester(Convert.ToString(emailBox.Text));
this.SpamRatingBox.Text = string.Format("{0:N1}%", Tester.countSpam / Tester.wordCount * 100);
this.WordsBox.Text = Tester.posSpam;
this.OutputPanal.Visible = true;
this.pictureBox1.Visible = false;
}
private void addButton_Click(object sender, EventArgs e)
{
scan.addSpam(Convert.ToString(addFlagBox.Text));
this.addFlagBox.Text = "";
}
}
答案 1 :(得分:1)
方法中的变量声明(就像你的那样)具有方法范围,因此其他方法无法看到它们。
相反,在 class 范围内声明变量,以便类的方法都可以看到它。
public partial class Spam_Scanner : Form
{
private Tester scan;
private void testButton_Click(object sender, EventArgs e)
{
scan = new Tester();
...
}
private void addButton_Click(object sender, EventArgs e)
{
scan.addSpam(Convert.ToString(addFlagBox.Text));
...
}
}
根据按钮单击的顺序,您可能希望在声明中而不是在testButton_Click方法中初始化变量,但这取决于您。要记住的重要一点是,范围可以看到自己的成员,以及它们嵌套的所有范围。因此,方法可以看到类范围变量,但不能看到彼此的。