2

我想输出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++] + "\\";
            }

    }
}
4

2 回答 2

3

初始化StrPath为空字符串 ("")在循环外声明它。您可能还需要考虑使用 a StringBuilder,因为Stringc# 中的 s 是不可变的。

于 2010-06-01T03:01:34.483 回答
3

我同意米奇小麦,但你可以解决你当前的初始化问题StrPath

string StrPath = string.Empty;

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

来自MSDN

C# 编译器不允许使用未初始化的变量。如果编译器检测到使用了可能尚未初始化的变量,则会生成 CS0165。

使用 new 创建对象的实例或赋值。

于 2010-06-01T03:01:35.687 回答