0

我正在为 .NET 使用 Delphi Prism。我需要从另一个 winform 方法调用我的 mainform 类中的公共方法。所以,最近了解了静态,我在我的程序中使用了它。静态或类 winform 效果很好,但将方法设为静态或类似乎不一样。

我的主窗体类中有一个名为 updateButtons 的方法。它根据用户的操作更新主窗体上的所有按钮和控件。此方法需要从另一个 winform 方法调用。因此,我将 UpdateButtons 方法设为静态或类。虽然现在我看到了要调用的方法,但编译器不喜欢。它不断引发以下错误,“无法在没有实例引用的情况下调用实例成员(任何控件)。”

如何使方法成为类或静态方法,并且仍然可以从 winform 访问控件?

具有静态或类方法的主类:

  MainForm = partial class(System.Windows.Forms.Form)
  private
  protected
    method Dispose(disposing: Boolean); override;
  public
    class method updateButtons;
  end;

更新按钮的定义:

class method MainForm.updateButtons;
begin    
        if SecurityEnabled then
                LoginBtn.Enabled := true       //All the lines where I call Buttons raise the error exception that I mentioned above.
        else
        begin
                UnitBtn.Enabled := true;
                SignalBtn.Enabled := true;
                AlarmBtn.Enabled := true;
                MakerBtn.Enabled := true;
                TrendBtn.Enabled := true;
                DxCommBtn.Enabled := (Scanning = false);
                TxBtn.Enabled := true;
                ControlBtn.Enabled := true;
                PIDBtn.Enabled := true;
                SystemBtn.Enabled := true;
                WinListBox.Enabled := true;
                WinBtn.Enabled := true;
                ShutdownBtn.Enabled := true;
                OptionBtn.Enabled := true;
                LoginBtn.Enabled:=false;
        end;
  end;
4

2 回答 2

1

这不能以您希望的方式工作。

类(或静态)方法在类上静态调用,而不是在特定对象实例上调用。

您可以多次实例化同一个表单类。然后你有几个表单的对象实例,它们可以同时打开或隐藏。

现在,当您调用静态方法时,应该更新这几种形式中的哪一种?编译器无法分辨,也不允许访问属于对象实例的字段或属性。

为此,您必须使该方法成为对象的普通方法(非类或静态),并且您需要检索具体表单对象实例的引用并在那里调用它。

于 2011-08-20T13:40:04.037 回答
0

由于我要执行的方法来自 MainForm Window Form 并从按钮事件中触发,因此我决定从 MainForm 而不是其他 winform 的 Button Click 事件中调用该方法。这具有相同的最终结果。另外,它更简单。

//This is just a sample code
MainForm = class(system.windows.forms.form)
private
    method ScanBtn_Click(sender: System.Object; e: System.EventArgs);
protected
public
    Method UpdateButtons;
end;

Method Mainform.UpdateButtons;
begin
   Button1.enabled:=true;
   Button1.text:='Start Scanning';
end;

method MainForm.ScanBtn_Click(sender: System.Object; e: System.EventArgs);
begin
    if not Scanning then
        stopthread:=true;

    dxCommWin.Scan(not Scanning);
    UnitWin.UpdateMenu;  
    UpdateButtons; <-------I call it here instead of from dxCommWin.Scan Method.
end;
于 2011-08-23T15:40:20.973 回答