我有一个奇怪的问题。我正在尝试编写一个查看 TextBox 的函数,如果它等于某个值,则将字符串的值更改为其他值。 这是我的代码:
我在 Main 中定义字符串:
string strDoorsOption1 = "test";
方法定义为:
public void optionCheck(TextBox txt, string str)
{
if (txt.Text == "0")
{
str = "+++";
}
else
{
str = "---";
}
}
我这样调用方法:
private void chkDoorsSafetyLaminated_CheckedChanged(object sender, EventArgs e)
{
checkBoxClick3(chkDoorsSafetyLaminated, txtDoorsSafety1);
optionCheck(txtDoorsSafety1, strDoorsOption1);
}
checkBoxClick3 是另一种按预期方式工作以更改文本框值的方法。 供引用,定义如下:
public void checkBoxClick3(CheckBox check, TextBox txt)
{
/* Determine the CheckState of the Checkbox */
if (check.CheckState == CheckState.Checked)
{
/* If the CheckState is Checked, then set the value to 1 */
txt.Text = "1";
}
else
{
/* If the CheckState is Unchecked, then set the value to 0 */
txt.Text = "0";
}
}
这有效...:
if (txtDoorsSafety1.Text == "0")
{
strDoorsOption1 = "+++";
}
else
{
strDoorsOption1 = "---";
}
但是当我调用 optionCheck(txtDoorsSafety1, strDoorsOption1);
时,它的行为就像该方法是空的一样。它完全编译,没有错误或警告,它什么都不做。
如有任何帮助,我们将不胜感激。
最佳答案
public void optionCheck(TextBox txt, string str)
按值传递字符串(就像所有引用一样),这意味着后面的赋值不会影响类级变量。您更改了本地副本,但没有使用它。
相反,通过 ref:
public void optionCheck(TextBox txt, ref string str)
称为:
optionCheck(txtDoorsSafety1, ref strDoorsOption1);
关于c# - 正确的语法;没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24270357/