【问题标题】:C# compile error Use of unassigned local variable [duplicate]C#编译错误使用未分配的局部变量[重复]
【发布时间】:2021-05-17 21:29:42
【问题描述】:

错误:使用未分配的局部变量“数据文件”

我知道这个问题被问了好几次,但我没有看到任何符合我要求的东西。请帮忙!

从以下代码检查文件是否存在,我收到以下错误,关于如何修复它的任何建议,我已经将 system.IO 包含在命名空间中

    public void Main()
    {
        // TODO: Add your code here

        string DataFilesLocation;
        string[] DataFiles ;

        DataFilesLocation = Dts.Variables["User::FolderPath"].Value.ToString();
        if (DataFiles.Length > 0)
        {
            Dts.Variables["User::Flag"].Value = true;
        }

        Dts.TaskResult = (int)ScriptResults.Success;
    }

提前感谢您的帮助。

【问题讨论】:

  • 您没有为DataFiles 赋值,但您正在尝试使用它的Length 字段。目前尚不清楚您希望 DataFiles.Length 测试什么,但也许您忘记为其赋值?也许使用Directory.GetFiles? (顺便说一句,我建议您遵循 C# 约定,以小写变量开头局部变量。)
  • 你没有初始化DataFiles,编译器禁止你从它“获取”一个值,直到你这样做。此规则适用于方法中声明的所有(局部)变量。
  • 有很多重复项可以解释为什么会出现这个错误,我真的很难相信你没有得到任何符合我要求的东西
  • 谢谢乔恩,我把它改成了字符串dataFilesLocation;字符串 [] 数据文件;你能告诉我如何初始化吗?这是我检查文件夹中是否存在文件的代码,如果是则标记为真,否则退出。

标签: c# ssis


【解决方案1】:

您需要在使用它们之前分配这两个变量,C# 中的最佳实践是在声明它们的行上分配变量,如果可以的话。

所以它应该看起来像:

  string dataFilesLocation = Dts.Variables["User::FolderPath"].Value.ToString();
  string[] dataFiles = System.IO.Directory.GetFiles(dataFilesLocation);

【讨论】:

    【解决方案2】:

    您永远不会为 DataFiles 分配任何内容。 尝试使用数组大小​​对其进行初始化并填充这些索引,或者为其分配一个数组。 E.G

    public void Main()
    {
        string DataFilesLocation;
        // initializes your variable, removing the error you are getting
        string[] DataFiles = new string[5];
        //populates the array with file names 
        for(int i=0 ; i< 5 ; i++){
            DataFiles[i]="FilePrefix"+i+".png";
        }
    
        DataFilesLocation = Dts.Variables["User::FolderPath"].Value.ToString();
        if (DataFiles.Length > 0)
        {
            Dts.Variables["User::Flag"].Value = true;
        }
    
        Dts.TaskResult = (int)ScriptResults.Success;
    }
    

    【讨论】:

    • 我相信你的意思是new string[5]而不是string[5]
    • @JonSkeet 谢谢伙计,已经有几个星期没接触 C#了,显然已经生锈了
    猜你喜欢
    • 2019-09-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多