2013-03-22 113 views
4

下面的函数产生错误,“未分配的局部变量‘intLast’的运用。我不知道我做错了。错误与局部变量

static string RemovePath(string strInput) 
    { 

     int intLast; 

     for (int i = 1; i < strInput.Length; i++) 
     { 
      if (strInput.Substring(i, 1) == @"\") 
      { 
       intLast = i; 
      } 
     } 

     string strOutput = strInput.Substring(strInput.Length - intLast); 

     return strOutput; 
    } 
+1

这不会删除使循环冗余的第一个路径部分吗?仅供参考有实用功能,如'System.IO.Path.GetFileName()' – 2013-03-22 11:57:50

+0

System.IO.Path.GetFileName()要容易得多!谢谢! – TroggleDorf 2013-03-22 12:48:00

回答

2

您使用的是可变​​在下面一行:

string strOutput = strInput.Substring(strInput.Length - intLast); 

但变量将只在一定条件下(strInput.Length > 1strInput.Substring(i, 1) == @"\")的值。为此,错误。

为了解决这个问题提供了声明中的缺省值:

int intLast = 0; // or any default value.

+0

谢谢!有效! – TroggleDorf 2013-03-22 12:10:55

0

初始化​​一些价值作为环能不保证该值被指定为循环的执行决定运行。

int intLast = 0; 

下面的几行是要求未分配的变量控制可能不会进入循环分配的值。

string strOutput = strInput.Substring(strInput.Length - intLast); 
0

由于您仅在条件内部指定​​,因此从编译器的角度来看,您可以在不初始化的情况下使用它。

即使您不希望曾经使用过,您应该在开始时将它初始化为某个默认值。

int intLast = 0 
0

您需要为​​指定一个默认值。

试试这个:

static string RemovePath(string strInput) 
{ 
    int intLast = 0; 

    for (int i = 1; i < strInput.Length; i++) 
    { 
     if (strInput.Substring(i, 1) == @"\") 
     { 
      intLast = i; 
     } 
    } 

    string strOutput = strInput.Substring(strInput.Length - intLast); 

    return strOutput; 
} 
0

只需编辑

int intLast = 0; 

整个代码看起来就像这样:

静态字符串RemovePath(字符串strInput) { INT intLast = 0;

for (int i = 1; i < strInput.Length; i++) 
    { 
     if (strInput.Substring(i, 1) == @"\") 
     { 
      intLast = i; 
     } 
    } 

    string strOutput = strInput.Substring(strInput.Length - intLast); 

    return strOutput; 
} 

您刚刚必须将​​初始分配为零。

0

你应该初始化你的​​变量。

编译器不知道像​​这样的变量将被分配,无论如何。

int intLast = 0; 
0

你应该初始化像

int intLast = 0; 

您的变量,因为它可能会保持未分配状态,如果它的代码不是如果条件达到。