使用未分配的局部变量'字典' [英] Use of unassigned local variable 'dictionary'

查看:115
本文介绍了使用未分配的局部变量'字典'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我在以下代码中指定了值,但是我收到了未使用的本地变量未使用的本地变量的错误:

I got the error Use of unassigned local variable 'dictionary' despite I assigned the value in the following code:

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: "))

任何人都可以帮我在这里吗? TIA

Can any one help me out here, pls? TIA

推荐答案

您需要在这里明确:

Dictionary<String, String> dictionary = null;

有可能性在尝试使用时不会分配在第二个尝试语句中,例如,如果在第一次尝试中立即抛出异常,则该字典不会指向任何内容。这不会阻止一个 null 引用异常(你将不得不处理),它只是让你的意图清楚了编译器。

There's the possibility it won't be assigned when you try to use it in your second try statement, for example if you throw an exception immediately in the first try, the dictionary wouldn't point to anything. This won't prevent a null reference exception (you'll have to handle that), it just makes your intent clear to the compiler.

这篇关于使用未分配的局部变量'字典'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆