2013-06-04 18 views
0

这是我的主要形式类里面我有Stop button click event接入到特定类的方法

public partial class MainWin : Form 
{ 
    private Job job = new... 

    private void btnStop_Click(object sender, EventArgs e) 
    { 
     job.state = 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

您无法访问类之外的私有方法。您是否允许将方法的访问说明符更改为internal/public? – Channs

回答

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 
    } 
} 

但是,只是猜测和看到这个小小的代码,你可能想重新设计你如何做的事情。

+0

如果您将状态设置为“false”,则会再次处理。 – CodeCaster

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(); 
     } 
    } 
} 

线程安全离开了锻炼。

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只读。如果你想让对象执行一些操作,这些方法将更适合这个。

相关问题