1

変数 asynchExecutions は変更されますが、参照変数は変更されません。
簡単な質問ですが、このコンストラクターのこの ref パラメーターが、渡された元の値を変更しないのはなぜですか?

public partial class ThreadForm : Form
{
    int asynchExecutions1 = 1;
    public ThreadForm(out int asynchExecutions)
    {
        asynchExecutions = this.asynchExecutions1;
        InitializeComponent();
    }

    private void start_Button_Click(object sender, EventArgs e)
    {
        int.TryParse(asynchExecution_txtbx.Text, out asynchExecutions1);

        this.Dispose();
    }

}
4

2 に答える 2

1

out パラメーターはメソッド呼び出しにのみ有効です。後で更新するために「保存」することはできません。

したがって、start_Button_Clickフォーム コンストラクターに渡された元のパラメーターを変更することはできません。

次のようなことができます。

public class MyType {
   public int AsynchExecutions { get; set; }
}

public partial class ThreadForm : Form
{
    private MyType type;

    public ThreadForm(MyType t)
    {
        this.type = t;
        this.type.AsynchExecutions = 1;

        InitializeComponent();
    }

    private void start_Button_Click(object sender, EventArgs e)
    {
        int a;
        if (int.TryParse(asynchExecution_txtbx.Text, out a))
            this.type.AsynchExecutions = a;

        this.Dispose();
    }

}

これにより、MyType のインスタンスの AsynchExecutions プロパティが更新されます。

于 2011-07-26T17:48:13.777 に答える
1

asynchExecutions が変更されていないことをどのように知っていますか? これを証明するテストケース コードを表示できますか?

ThreadForm の構築時に asyncExecutions が 1 に設定されるようです。ただし、start_Button_Click を呼び出すと、asyncExecutions1 がテキスト ボックスの値に設定されます。

これは、テキスト ボックスの値に asyncExecutions を設定しません。これらは値の型だからです。コンストラクターでポインターを設定していません。

値型と参照型の動作が混同されているようです。

2 つのコンポーネント間で状態を共有する必要がある場合は、静的状態コンテナーを使用するか、共有状態コンテナーを ThreadForm のコンストラクターに渡すことを検討してください。例えば:

 public class StateContainer
 {
     public int AsyncExecutions { get; set;}
 }

public class ThreadForm : Form
{
     private StateContainer _state;

     public ThreadForm (StateContainer state)
     {
          _state = state;
          _state.AsyncExecutions = 1;
     }

     private void start_Button_Click(object sender, EventArgs e)
     {
          Int.TryParse(TextBox.Text, out _state.AsyncExecutions);
     }
}
于 2011-07-26T17:50:34.150 に答える