c# - 使用未分配的局部变量 'dictionary'

标签 c# dictionary

尽管我在以下代码中分配了值,但我仍收到错误 Use of unassigned local variable 'dictionary':

private static void UpdateJadProperties(Uri jadUri, Uri jarUri, Uri notifierUri)
    {
        Dictionary<String, String> dictionary;

        try
        {
            String[] jadFileContent;

            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader(jadUri.AbsolutePath.ToString()))
            {
                Char[] delimiters = { '\r', '\n' };
                jadFileContent = sr.ReadToEnd().Split(delimiters, System.StringSplitOptions.RemoveEmptyEntries);
            }

            // @@NOTE: Keys contain ": " suffix, values don't!
            dictionary = jadFileContent.ToDictionary(x => x.Substring(0, x.IndexOf(':') + 2), x => x.Substring(x.IndexOf(':') + 2));

        }
        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }

        try
        {
            if (dictionary.ContainsKey("MIDlet-Jar-URL: "))
            {
                // Change the value by Remove follow by Add

            }
        }
        catch (ArgumentNullException ane)
        {

            throw;
        }

    }

错误来自行:

if (dictionary.ContainsKey("MIDlet-Jar-URL: "))

有人可以帮我解决这个问题吗?时间差

最佳答案

你需要在这里明确:

Dictionary<String, String> dictionary = null;

当您尝试在第二个 try 语句中使用它时,可能它不会被分配,例如,如果您在第一次尝试中立即抛出异常,字典不会指向任何东西。这不会阻止 null 引用异常(你必须处理它),它只是让编译器清楚你的意图。

关于c# - 使用未分配的局部变量 'dictionary',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3066792/

相关文章:

c# - 当属性名称包含空格和保留字时将 JSON 映射到 C# 类

c# - 创建 LINQ 实体类时损坏 POCO 域模型?

python - 如何重新排列字典键的顺序?

python - 格式化要在 jinja2 模板中呈现的嵌套 Python 字典的最佳方法

python - 将深度很大的嵌套字典(森林)写入文本文件

c# - .NET 中是否有 Dictionary 的替代方案?

C#:如何将 TimeSpan 值转换为 double 值?

c# - EF 模型第一个 : Subclass object does not appear in Context

c# - 存储在通用集合中后重载和多态行为发生变化

python - 如何使用字典将数字代码翻译成单词