如何在程序中进一步使用switch语句中指定的变量?

Riz*_*Riz 1 c# scope switch-statement unity-game-engine

我试图根据当前场景的索引读取不同的文本文件(在Unity术语中).所以,我决定使用如下的switch语句:

void MyReadString()
{
    Scene currentScene = SceneManager.GetActiveScene(); // Unity command to get the current scene info
    int buildIndex = currentScene.buildIndex; // Unity command to get the current scene number
    string path = string.Empty; // Create an empty string variable to hold the path information of text files
    switch (buildIndex)
    {
        case 0:
            string path = "Assets/Scripts/some.txt"; //It says here that the variable path is assigned but never used!
            break;
        case 1:
            string path = "Assets/Scripts/another.txt"; //Same here - assigned but never used. 
            break;
        // and many other cases - atleast 6 more
    } 
    StreamReader reader = new StreamReader(path); // To read the text file
    // And further string operations here - such as using a delimiter, finding the number of values in the text etc
}
Run Code Online (Sandbox Code Playgroud)

如果我注释掉这条线:

string path = string.Empty;
Run Code Online (Sandbox Code Playgroud)

然后,

StreamReader reader = new StreamReader(path); // says here the name "path" does not exist in the current context.
Run Code Online (Sandbox Code Playgroud)

我知道这必须对switch语句的范围做些什么.但是,将交换机外部的字符串变量声明为"Empty"不起作用.如果我可以在Switch语句中分配字符串值并稍后使用该值,请告诉我.或者,如果不可能,请建议我解决方法.

Pro*_*mer 5

您遇到问题是因为您在switch语句中再次重新声明了path变量.仅在switch语句之外声明一次,然后在switch语句中分配它.

void MyReadString()
{
    Scene currentScene = SceneManager.GetActiveScene(); // Unity command to get the current scene info
    int buildIndex = currentScene.buildIndex; // Unity command to get the current scene number
    string path = null;
    // Create an empty string variable to hold the path information of text files
    switch (buildIndex)
    {
        case 0:
            path = "Assets/Scripts/some.txt"; //It says here that the variable path is assigned but never used!
            break;
        case 1:
            path = "Assets/Scripts/another.txt"; //Same here - assigned but never used. 
            break;
            // and many other cases - atleast 6 more
    }
    StreamReader reader = new StreamReader(path); // To read the text file                                               // And further string operations here - such as using a delimiter, finding the number of values in the text etc
}
Run Code Online (Sandbox Code Playgroud)

不相关,但请注意,这不是如何在Unity中读取文件.在构建项目时代码将失败.使用Resources API或使用Assetbundles.