在多个函数之间使用对象 [英] Use object between multiple functions
本文介绍了在多个函数之间使用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建垃圾邮件检查器.一种方法扫描电子邮件,另一种方法将已知标志添加到要检查的单词和短语数组中;这两种方法都是 Tester
类的一部分.目前我每个方法都有一个按钮,但是每个事件都会创建自己的垃圾邮件对象.如何让两个事件使用同一个对象,让扫描识别我刚刚添加的标志?
I am creating a spam email checker. One method scans the email, another adds a known flag to an array of words and phrases to check against; both methods are part of Tester
class. Currently I have a button per method, however each event creates its own spam object. How do I get both events to use the same object, allowing the scan to recognize the flag I just added?
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 = "";
}
}
}
推荐答案
移动 Tester
变量到类字段,像这样:
Move the Tester
variable to the class field, like this:
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 = "";
}
}
这篇关于在多个函数之间使用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文