简体   繁体   English

Windows窗体的C#类耦合

[英]C# Class Coupling with Windows Forms

I am currently attempting to modify an existing Windows Forms project to better comply with SOLID principles. 我目前正在尝试修改现有的Windows Forms项目以更好地符合SOLID原则。 Currently there is a main class that initalizes the form and all the logic is then processed in a logic class. 当前有一个初始化该表格的主类,然后在逻辑类中处理所有逻辑。

This creates high coupling and isn't untestable because all the locic changes things on the main form. 这会产生较高的耦合度,并且不是不可测试的,因为所有位置都会改变主窗体上的内容。 For example I have a button to refresh a grid, this calls the logic class to build the data and then this refreshes the grid. 例如,我有一个刷新网格的按钮,它调用逻辑类来构建数据,然后刷新网格。 Below is a short example of how it currently looks. 以下是当前外观的简短示例。

public partial class XpressReports : Form
{
    private void refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        try
        {
            Globals.DataLogic.RefreshData();
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message);
        }
    }
}

public class DataLogic
{
    public void RefreshData()
    {
        dataset selectedTableList;

        selectedTableList = GetNonRefreshFlagColumnIdList();

        dataGridView.Columns.Clear();
        dataGridControl.DataSource = null;
        dataGridControl.DataSource = dataViewData.Tables[0];
    }
}

Im not sure what the ideal approach for something like this would be. 我不确定类似的理想方法是什么。 I could create a new method do update the datasource in the main form class but then there would still be a lot of back and forward between the two. 我可以创建一个新方法来更新主表单类中的数据源,但是在两者之间仍然会有很多来回操作。 What is the best way of seperating this kind of thing out? 分离出这种东西的最好方法是什么?

The clearer way I have seen so far in windows forms is using a Presente pattern. 到目前为止,我在Windows窗体中看到的更清晰的方法是使用Presente模式。

You can either call directly your presenter from the form or trigger events the preseter is subscribed to. 您可以直接从表单中调用演示者,也可以触发预订者订阅的事件。

The presenter will keep a reference to the view(form) and will call the appropriate methods on it. 演示者将保留对视图(窗体)的引用,并在其上调用适当的方法。

Use an interface for the view methods to decouple your presenter from your actual form. 使用界面作为查看方法,以使演示者与实际表单脱钩。

Something like the following pseudocode: 类似于以下伪代码:

 public interface IView 
 {
     event EventHandler Initialise;
     void SetData(MyData data)
 }

 public class Presenter
 {
    ....

     public Presenter(IView view ) 
     { 
         _view = view;
         _view.Initialise += OnViewInitialise; 
     }

     public void OnViewInitialise() 
     {
          var data = _repository.GetData();
          _view.SetData(data);
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM