【问题标题】:Reuse code from class to class从一个类到另一个类重用代码
【发布时间】:2014-08-28 23:19:43
【问题描述】:

我有 2 个winforms,分别称为AppNamespace.MYFormAnotherNamespace.AnotherForm
他们都有一个按钮。

当用户点击AnotherNamespace.AnotherForm 的按钮时,我想点击AppNamespace.MYForm 上的按钮。

但是,有一个约束 AnotherNamespace 不能使用 AppNamespace
这使我无法这样做:

AppNamespace.MYForm firstForm = new AppNamespace.MYForm();
firstForm.button.PerformClick();

有什么想法吗?

【问题讨论】:

  • 为什么你不尝试注册第二个按钮事件并在第一个按钮被点击时触发它
  • @MoezRebai,即将在两个不同的事件上执行相同的代码。无论如何,您能否发布一些代码如何执行此操作,以便我了解这是否可以解决问题?谢谢
  • AnotherForm 如何知道MyForm 的存在?并获得参考?做AppNamespace可以用AnotherNamespace吗?
  • @Alex, AnotherForm 没有对来自第二个命名空间的表单的引用。 Appnamespcase 知道 AnotherNamespace。谢谢。
  • 您的问题解决了吗?

标签: c# winforms namespaces code-reuse


【解决方案1】:

通过编辑 Form2.Designer.cs 在第二个表单 public 上创建 Button

public System.Windows.Forms.Button button1;

并使用第一种形式注册其Click

private void Form1_Load(object sender, EventArgs e)
{
    // or whatever you do to create the 2nd form..
    AnotherNamespace.Form2 F2 = new AnotherNamespace.Form2();
    F2.Show();
    // register the click:
    F2.button1.Click += button2_Click;
}

或者以第二种形式创建Property

public Button myButton { get; set;  }

并将其设置为Button

public Form2()
{
   InitializeComponent();
   myButton = button1;
}

现在您可以像这样注册它的Click

F2.myButton.Click += button2_Click;

【讨论】:

    【解决方案2】:

    手动执行任何控件的事件都是不好的做法。创建单独的方法并改为执行它。

    您可以创建接口,然后将其实现到两种形式。接口应该包含一个方法PerformClick

    public Interface IMyInterface
    {
        void PerformClick(string _module);
    }
    
    public class Form1 : IMyInterface
    {
       public void IMyInterface.PerformClick(string _module) 
       {
          //CODE HERE
          if (Application.OpenForms["Form2"] != null && _module != "Form2")
              ((IMyInterface)Application.OpenForms["Form2"]).PerformClick(_module);
       }
    
       private void button1_Click(object sender, EventArgs e)
       {
           this.PerformClick(this.Name);
       }
    }
    
    
    public class Form2 : IMyInterface
    {
       public void IMyInterface.PerformClick() 
       {
          //CODE HERE
          if (Application.OpenForms["Form1"] != null && _module != "Form1")
              ((IMyInterface)Application.OpenForms["Form1"]).PerformClick(_module);
       }
    
       private void button1_Click(object sender, EventArgs e)
       {
           this.PerformClick(this.Name);
       }
    }
    

    【讨论】:

      【解决方案3】:

      在帮助类/另一个命名空间中分离按钮点击代码,并在按钮点击中调用它。

      您可以通过调用助手命名空间和方法在任何命名空间中使用该方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多