c# - 局部变量错误

标签 c# variables scope

以下函数生成错误,“使用未分配的局部变量‘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;
    }

最佳答案

您正在以下行中使用变量 intLast:

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

但变量只有在某些条件下才会有值(strInput.Length > 1strInput.Substring(i, 1) == @"\") .因此错误。

要解决此问题,请在声明中提供默认值:

int intLast = 0;//或任何默认值。

关于c# - 局部变量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15569634/

相关文章:

c# - 将除以 10 的整数四舍五入到最接近的整数

c# - 如何使用 NSubstitute 模拟惰性类

javascript - Codepen 在预期很少的项目时返回空数组

javascript - 无法在 JavaScript Promise 中为变量设置正确的范围

Javascript:列出同一范围内的所有变量(iframe)

php - 在 PHP 中查看生成和保留名称

c# - 将查询添加到字段时,NEST Elasticsearch空响应

c# - 如何在 ASP.NET 中以编程方式创建 <h1> 标记?

android - 在 react-native 中从 java 代码访问 java 变量到 javascript 代码

objective-c - 以编程方式创建变量