gpt4 book ai didi

c# - C# 中的路径字符串连接问题

转载 作者:行者123 更新时间:2023-12-02 17:24:47 25 4
gpt4 key购买 nike

我想输出D:\Learning\CS\Resource\Tutorial\C#LangTutorial但无法工作。编译器错误错误CS0165:使用未分配的局部变量'StrPathHead请给我一些关于如何纠正我的代码或针对我的案例的其他更好解决方案的建议。谢谢。

static void Main(string[] args)
{
string path = "D:\\Learning\\CS\\Resource\\Book\\C#InDepth";
int n = 0;

string[] words = path.Split('\\');
foreach (string word in words)
{

string StrPathHead;
string StrPath;
Console.WriteLine(word);

if (word == "Resource")
{
StrPath = StrPathHead + word + "\\Tutorial\\C#LangTutorial";
}
else
{
StrPathHead += words[n++] + "\\";
}

}
}

最佳答案

我同意 Mitch Wheat 的观点,但是你可以通过初始化 StrPath 来解决当前的问题。

string StrPath = string.Empty;

正如其他人所说,声明 StrPath在循环之外。

来自MSDN

The C# compiler does not allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates CS0165.

Use new to create an instance of an object or assign a value.

关于c# - C# 中的路径字符串连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2947057/

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