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 时 asynchExecutions 将设置为 1。但是,当您调用 start_Button_Click 时,您将 asyncExecutions1 设置为文本框中的值。

这不会将 asyncExecutions 设置为文本框中的值,因为这些是值类型。您没有在构造函数中设置指针。

在我看来,您对值类型和引用类型的行为感到困惑。

如果需要在两个组件之间共享状态,可以考虑使用静态容器,或者将共享状态容器传递给 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 回答