gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:21 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com