C#一次初始化局部变量 [英] C# Initialize local variable once

查看:53
本文介绍了C#一次初始化局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我的问题完全是愚蠢的,但我必须知道答案.

I assume my question will be totally stupid but I have to know the answer.

在这种情况下是否可以只初始化一次变量?

Is it possible to initialize a variable just once in this situation?

    static void Main()
    {
        while (true)
        {
            MethodA();
            MethodB();
        }
    }

    private static void MethodA()
    {
        string dots = string.Empty;    // This should be done only once

        if (dots != "...")
            dots += ".";
        else
            dots = string.Empty;

        Console.WriteLine(dots + "\t" + "Method A");
        System.Threading.Thread.Sleep(500);
    }

    private static void MethodB()
    {
        string dots = string.Empty;    // This should be done only once

        if (dots != ".....")
            dots += ". ";
        else
            dots = string.Empty;

        Console.WriteLine(dots + "\t" + "Method B");
        System.Threading.Thread.Sleep(500);
    }

我当然可以从方法中初始化字符串点,但是我不想在代码中搞乱,而且也不能在任何其他循环中完成(例如for).有什么想法可以解决这个问题吗?还是我如此愚蠢地想到正常情况?

Of course I can initialize string dots out of method but I don't want to do mess in the code, and this can't be done in any other loop too (like for). Any ideas how solve this or am I so stupid to think normally?

谢谢.

我将示例代码更改为更加实用.所需的输出应为:

I've changed the sample code to be more practical. Desired output should be:

.    Method A
.    Method B
..   Method A
..   Method B
...  Method A
...  Method B
     Method A
.... Method B
.    Method A
.....Method B

等等.等

推荐答案

您说过,您不想将点保留在Method之外(在Method的类中),那么您必须从Method返回值,以便您至少可以在以后传递它,从而保持其状态.

You said you don't want to keep the dots out side of Method (in the Method's class), then you must return the value from Method so that you can at least pass it in later on, thus persisting its state.

string Method(string dot = string.Empty)
{
   if(dot == "...") return string.Empty;
   else return dot + ".";
}

var result = Method(Method(Method(Method(Method(Method()))))) // etc...

您编辑的问题不会使您的最初问题更加实用.它仍然遭受相同的问题:您想要X,但C#没有X.请改用C ++或VB.NET.

Your edited question does not make your initial problem more practical. It still suffers from the same problem: You want X but C# does not have X. Use C++ or VB.NET instead.

您问题的答案

在这种情况下是否可以只初始化一次变量?"

"Is it possible to initialize a variable just once in this situation?"

抱歉,不!

这篇关于C#一次初始化局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆