为什么这个 ref 参数没有改变传入的值?
变量 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();
}
}
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.asynchExecutions1;
InitializeComponent();
}
private void start_Button_Click(object sender, EventArgs e)
{
int.TryParse(asynchExecution_txtbx.Text, out asynchExecutions1);
this.Dispose();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你怎么知道 asynchExecutions 没有改变?你能展示你的测试用例代码来证明这一点吗?
看起来,在构造 ThreadForm 时,asynchExecutions 将被设置为 1。但是,当您调用 start_Button_Click 时,您将 asyncExecutions1 设置为文本框中的值。
这不会将 asyncExecutions 设置为文本框中的值,因为这些是值类型。您没有在构造函数中设置指针。
在我看来,您对值类型与引用类型的行为感到困惑。
如果需要在两个组件之间共享状态,请考虑使用静态容器,或者将共享状态容器传递给 ThreadForm 的构造函数。例如:
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:
out 参数仅适用于方法调用,您无法“保存”它以供以后更新。
因此,在
start_Button_Click
中,您无法更改传递给表单构造函数的原始参数。您可以执行以下操作:
这将更新 MyType 实例的 AsynchExecutions 属性。
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:
That will update the AsynchExecutions property of the instance of MyType.