这是我的主要表单类,里面有Stop button click event
:
public partial class MainWin : Form
{
private Job job = new...
private void btnStop_Click(object sender, EventArgs e)
{
job.state = true;
}
}
单击我的停止按钮后,我将我的作业类成员从false更改为true,我想要做的是当此变量更改为true时,我想访问作业类中的特定方法并执行某些操作。
public class Job
{
public bool state { get; set; }
private void processFile() // i want access to this method in order to change other class state
{
// do work
}
}
我该怎么做?
答案 0 :(得分:2)
很难说出你究竟是什么意思,但是在设置属性时调用方法的一种方法是扩展auto属性并完全按照这种方式执行。
public class Job
{
private bool state;
public bool State
{
get { return this.state; }
set
{
this.state = value;
processFile();
}
private void processFile()
{
// do work
}
}
然而,只是猜测并看到这些代码,你可能想重新设计你的工作方式。
答案 1 :(得分:0)
像这样创建Job
类:
public class Job
{
private bool _isRunning = false;
public bool IsRunning { get { return _isRunning; } }
public void StartProcessing()
{
if (_isRunning)
{
// TODO: warn?
return;
}
ProcessFile();
}
public void StopProcessing()
{
if (!_isRunning)
{
// TODO: warn?
return;
}
// TODO: stop processing
}
private void ProcessFile()
{
_isRunning = true;
// do your thing
_isRunning = false;
}
}
然后像这样消费:
public partial class MainWin : For
{
private Job _job = new Job();
private void StartButton_Click(object sender, EventArgs e)
{
if(!_job.IsRunning)
{
_job.StartProcessing();
}
}
private void StopButton_Click(object sender, EventArgs e)
{
if(_job.IsRunning)
{
_job.StopProcessing();
}
}
}
线程安全被遗漏为锻炼。
答案 2 :(得分:0)
如果真的不想公开私有方法,你可以这样做:
public class Job
{
private bool state;
public bool State
{
get
{
return state;
}
set
{
if (state != value)
{
state = value;
OnStateChanged();
}
}
}
private void OnStateChanged()
{
if (state) // or you could use enum for state
Run();
else
Stop();
}
private void Run()
{
// run
}
private void Stop()
{
// stop
}
}
但您应该考虑创建公开的Job.Run
方法并将Job.State
只读。如果您希望对象执行某些操作,则该方法将更适合此。