【问题标题】:out keyword not working with method in method in C#out 关键字不适用于 C# 中的方法中的方法
【发布时间】:2015-01-09 19:50:35
【问题描述】:

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

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

我已经列出了次要的主要内容,它只是分成四行,我测试过,并将 StringD 设置为“测试”

在我的主目录

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

Secondary Main(这个可行,但我宁愿使用第一个)

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# methods out


【解决方案1】:

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

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

    StringE = StringA;
    BoolB = BoolA;
}

然后这样称呼它:

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

这样Method2StringD 被传递给方法之前被调用。

【讨论】:

  • 当然,这绝对可以解决您的问题,但我建议您在调用 Method1 之前,先单独调用 Method2。将它组合成一行绝不是对程序的优化,因为需要分配相同的变量并且以相同的顺序进行相同的函数调用,但是您刚刚使这个函数调用链增加了 50 倍阅读、理解和调试,只为节省一行代码。恰当的例子:首先提出这个问题的事实。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 2021-09-16
  • 2018-11-22
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多