0

Delphi Prismfor.NETを使用しています。メインフォームクラスのパブリックメソッドを別のwinformメソッドから呼び出す必要があります。それで、最近静的について学んだので、私はそれを私のプログラムで使用しました。静的またはクラスのwinformはうまく機能しますが、メソッドを静的またはクラスにすることは同じようには機能しないようです。

メインフォームクラスにupdateButtonsというメソッドがあります。ユーザーの操作に応じて、メインフォームのすべてのボタンとコントロールを更新します。このメソッドは、別のwinformメソッドから呼び出す必要があります。そこで、そのUpdateButtonsメソッドを静的またはクラスにしました。今、私は呼び出すメソッドを見ていますが、コンパイラーは好きではありません。「インスタンス参照なしでインスタンスメンバー(任意のコントロール)を呼び出すことはできません」というエラーが発生し続けます。

メソッドをクラスまたは静的にし、WinFormからコントロールにアクセスするにはどうすればよいですか?

静的メソッドまたはクラスメソッドを持つメインクラス:

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

updatebuttonの定義:

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 からのもので、ボタン イベント内から起動されるため、他の winform からではなく、MainForm の 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 に答える