c# - 正确的语法;没有结果

标签 c#

我有一个奇怪的问题。我正在尝试编写一个查看 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/

相关文章:

C#GenerateCodeFromCompileUnit 正在生成带有特殊字符的代码 [Microsoft.CSharp.CSharpCodeProvider]

c# - 使用 File.Create 和 Delete 进行单元测试,但出现 "file used by other process"异常

c# - C# 中有两种调用方法,并且只保存第一个调用结果

c# - List.add 使用 Linq

c# - 如何按列表使用的对象内的元素对列表进行排序?

c# - 工厂方法和泛型

c# - TryUpdateModel 和 System.MissingMethodException

c# - 如何对 Create POST 进行单元测试?

c# - HTML 表是否比 ASP.NET MVC 中的 Gridview 更好?

c# - 我是否需要 web.config 值配置 -> 运行时 -> System.Web.Extensions 的 assemblyBinding?