C# 中的路径字符串连接问题
我想输出 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++] + "\\";
}
}
}
I want to output D:\Learning\CS\Resource\Tutorial\C#LangTutorial
But can't work. Compiler error error CS0165: Use of unassigned local variable 'StrPathHead
Please give me some advice about how to correct my code or other better solution for my case. Thank you.
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++] + "\\";
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意 Mitch Wheat 的观点,但是你可以通过初始化
StrPath
string StrPath = string.Empty;
来解决当前的问题,正如其他人所说,声明
StrPath
> 在循环之外。来自 MSDN
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
将
StrPath
初始化为空字符串 ("")并在循环外部声明它。您可能还需要考虑使用StringBuilder
,因为 C# 中的String
是不可变的。Initialize
StrPath
to the empty string ("") and declare it outside your loop. You may also want to consider using aStringBuilder
sinceString
s in c# are immutable.