out 关键字不适用于 C# 中方法中的方法

本文关键字:方法 适用于 关键字 不适用 out | 更新日期: 2023-09-27 18:36:54

我正在尝试在一个方法中使用 out 关键字返回一个字符串,并在另一个方法中使用该方法和 out 的返回结果。 但是,即使我看到它在通过 Method2 后立即在调试中设置了变量 StringD,但 StringA 在方法 1 开始时显示为空白。

我希望当它在 Method2 中将 StringD 设置为"测试"时,它会立即传递回 main 以在 Method1 中使用,这样就可以分两行完成。 这是有意的还是 C# 中的错误? 我必须用 4 行来代替吗?

我已经列出了辅助主电源,它只是将其分成四行,我对其进行了测试,并且可以将StringD设置为"测试"

在我的主

String StringD = "";
Method1(StringD, Method2(out StringD, ""));

次要主(这个有效,但我宁愿使用第一个)

String StringD = "";
Boolean BoolC = false;
BoolC = Method2(out StringD, "");
Method1(StringD, BoolC);

我的方法

private void Method1(String StringA, Boolean BoolA)
{
    String StringE = "";
    Boolean BoolB = false;
    StringE = StringA;
    BoolB = BoolA;
}
private Boolean Method2(out String StringB, String StringC)
{
    StringB = "";
    if (StringC == "")
    {
        StringB = "Test";
        return true;
    }
    else
    {
       return false;
    }
 }

out 关键字不适用于 C# 中方法中的方法

您可以在Method1中更改参数顺序

private void Method1(Boolean BoolA, String StringA)
{
    String StringE = "";
    Boolean BoolB = false;
    StringE = StringA;
    BoolB = BoolA;
}

然后这样称呼它:

Method1(Method2(out StringD, ""), StringD);

这样,在将StringD传递给方法之前调用Method2