从我的主表单类访问到特定的类方法



这是我的主要表单类,里面有Stop button click event:

public partial class MainWin : Form
{
    private Job job = new...
    private void btnStop_Click(object sender, EventArgs e)
    {
       job.state = 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
    }
}

很难说清楚您的确切意思,但是在设置属性时调用方法的一种方法是将auto属性展开并执行此操作。

public class Job
{
    private bool state;
    public bool State
    {
       get { return this.state; }
       set
       {
          this.state = value;
          processFile();
       } 
    private void processFile()
    {
       // do work
    }
}

然而,只是猜测和看到这一小段代码,您可能想要重新设计您的操作方式

如果真的不想暴露你的私有方法,你可以这样做:

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只读。

如果您希望对象执行某些操作,则方法将更适合此。

像这样创建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();
        }
    }
}

不考虑线程安全

最新更新