开发者

Why isn't this ref parameter changing the value passed in?

The variable asynchExecutions does get changed, but it doesn't change the reference variable.

Simple question, why isn't this ref parameter in this constructor changing the original value passed in?

public partial class ThreadForm : Form
{
    int asynchExecutions1 = 1;
    public ThreadForm(out int asynchExecutions)
    {
        asynchExecutions = this.asynchExecut开发者_开发问答ions1;
        InitializeComponent();
    }

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

        this.Dispose();
    }

}


How do you know that asynchExecutions is not changing? Can you show your testcase code that proves this?

It appears that on constructing ThreadForm asynchExecutions will be set to 1. However when you call start_Button_Click, you set asyncExecutions1 to the value in the text box.

This WILL NOT set asyncExecutions to the value in the text box, because these are value types. You are not setting a pointer in the constructor.

It seems to me that you are confused between the behavior of value types versus reference types.

If you need to share state between two components, consider using a static state container, or passing in a shared state container to the constructor of ThreadForm. For example:

 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);
     }
}


The out parameter is only good for the method call, you can't "save" it to update later.

So in your start_Button_Click, you can't change the original parameter passed to your form constructor.

You could do something like:

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();
    }

}

That will update the AsynchExecutions property of the instance of MyType.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜