3

カスタム XNA GUI でメソッドを引数として受け入れる Button クラスを作成しようとしています。これは、Pythontkinterで呼び出される関数を設定する 方法と同様Button.config(command = a_method)です。

ここここここでデリゲートをパラメーターとして使用することについて読んだことがありますが、それを機能させることにこれ以上近づいていないようです。私はデリゲートがどのように機能するかを完全には理解していませんが、いくつかの異なることを試してみましたが失敗しFunc<int>? command = nullました.commandnullFunc cannot be nullable type

理想的には、コードは次のようになります。

class Button
{
//Don't know what to put instead of Func
Func command;

// accepts an argument that will be stored for an OnClick event
public Button(Action command = DefaultMethod)
  {
    if (command != DefaultMethod)
    {
       this.command = command;
    }
  }
}

しかし、私が試したことはすべてうまくいかないようです。

4

3 に答える 3

1

デフォルトのパラメーターは、コンパイル時定数でなければなりません。C# では、デリゲートを定数にすることはできません。実装で独自のデフォルトを提供することで、同様の結果を得ることができます。(ここではWinformを使用しています)

    private void button1_Click(object sender, EventArgs e)
    {
        Button(new Action(Print));
        Button();
    }

    public void Button(Action command = null)
    {
        if (command == null)
        {
            command = DefaultMethod;
        }
        command.Invoke();
    }

    private void DefaultMethod()
    {
        MessageBox.Show("default");
    }

    private void Print()
    {
        MessageBox.Show("printed");
    }
于 2012-08-23T18:58:27.583 に答える
0

null 可能ではないというエラーが表示されます。Func<T>これは参照型であり、値型のみが null 可能です。

Func<T>パラメータのデフォルトをnullにするには、単純に次のように記述します。

Func<int> command = null
于 2012-08-23T18:54:33.400 に答える
0

デフォルト値に興味がある場合、このようなものは機能しますか?

class Button
{
  //Don't know what to put instead of Func
  private readonly Func defaultMethod = ""?
  Func command;

  // accepts an argument that will be stored for an OnClick event
  public Button(Action command)
  {
    if (command != defaultMethod)
    {
       this.command = command;
    }
  }
}
于 2012-08-23T18:40:41.790 に答える