c# - 如何在程序中进一步使用switch语句内分配的变量?

标签 c# unity3d scope switch-statement

我正在尝试根据当前场景的索引(在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
}


如果我将这一行注释掉:

string path = string.Empty;


然后,

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


我知道这与switch语句的范围有关。但是,将开关外部的字符串变量声明为“空”是行不通的。请让我知道是否可以在Switch语句中分配字符串值并稍后使用该值。或者,如果不可能,请向我建议解决方法。

最佳答案

您遇到问题是因为您在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
}




无关,但请注意,这不是在Unity中读取文件的方式。构建项目时,该代码将失败。使用Resources API或使用Assetbundles

关于c# - 如何在程序中进一步使用switch语句内分配的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51631887/

相关文章:

c# - VS2019 Roslyn编译器通用约束方法解析

c# - Unity Linux 包导出正在修改我的 DLL

unity3d - Unity Build 安装但导致黑屏

css - 保护库组件不被消费者设计样式的标准方法

c# - 更改 slider 缩略图工具提示的文本/数据格式

c# - 'ClosedXML.Excel.XLWorkbook' 的类型初始值设定项抛出异常

unity3d - 如何在运行时存储或读取动画剪辑数据?

scope - Kotlin - 限制扩展方法范围

javascript - 使用 console.log 中的 Javascript 变量作为引用

c# - 为什么我的异步回调在同一个线程中运行?