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

Initialize StrPath to the empty string ("") and declare it outside your loop. You may also want to consider using a StringBuilder since Strings in c# are immutable.

于 2010-06-01T03:01:34.483 に答える
3

I agree with Mitch Wheat, but you could solve your current problem initializating StrPath

string StrPath = string.Empty;

And as other people say, declare StrPath outside of the loop.

From 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.

于 2010-06-01T03:01:35.687 に答える