C#NullReferenceException未处理

时间:2011-03-18 10:16:45

标签: c# wpf

我正在尝试使用我在项目中在网上找到的CSV解析器。问题是当我尝试将字符串转换为Tag并且我的集合没有填充时,我得到一个空引用异常。有人可以帮忙吗?感谢

CSV解析器

private static IEnumerable<string[]> parseCSV(string path)
    {
        List<string[]> parsedData = new List<string[]>();

        try
        {
            using (StreamReader readFile = new StreamReader(path))
            {
                string line;
                string[] row;

                while ((line = readFile.ReadLine()) != null)
                {
                    row = line.Split(',');
                    parsedData.Add(row);
                }
            }
        }
        catch (Exception e)
        {
            System.Windows.MessageBox.Show(e.Message);
        }

        return parsedData;
    }

标记类

  public class Tag
    {
        public Tag(string name, int weight)
        {
            Name = name;
            Weight = weight;
        }

        public string Name { get; set; }
        public int Weight { get; set; }

        public static IEnumerable<Tag> CreateTags(IEnumerable<string> words)
        {
            Dictionary<string, int> tags = new Dictionary<string, int>();

            foreach (string word in words)
            {
                int count = 1;
                if (tags.ContainsKey(word))
                {
                    count = tags[word] + 1;
                }

                tags[word] = count;
            }

            return tags.Select(kvp => new Tag(kvp.Key, kvp.Value));
        }
    }

2 个答案:

答案 0 :(得分:2)

在使用之前验证所有方法参数!

  

它突破了这一行:foreach(单词中的字符串单词)

请记住,foreach循环通过在迭代的集合上调用GetEnumerator来工作。也就是说,foreach循环导致调用words.GetEnumerator,如果words为空则此调用失败。

因此,请在words方法的最开头添加一个警卫来验证您的参数CreateTags

if (words == null)
{
    throw new ArgumentNullException("words");
}

这有助于您在代码中找到null传递到CreateTags的位置,然后您可以继续修复调用代码。

建议:尽可能避免null

作为一般规则,请尽量避免使用null值。例如,当您的代码处理项目的集合和集合时,您可以确保它也可以正确处理空集合。在第二步中,确保永远不要使用null来表示空集合;相反,使用例如LINQ的Enumerable.Empty<TItem>()生成器用于创建空集合。

你可以开始这样做的地方是CreateTags方法,确保无论输入是什么,该方法总是返回一个有效的,非空(但可能是空的)集合:

if (words == null)
{
    return Enumerable.Empty<Tag>();  // You could do without LINQ by writing:
                                     // return new Tag[] { };
}

答案 1 :(得分:0)

每个方法都应该对它接受的参数进行健全性检查,以确保参数是有效的输入参数。我可能会做类似

的事情
public static IEnumerable<Tag> CreateTags(IEnumerable<string> words)
    {
        if(words==null)
        {
           //either throw a new ArgumentException or
           return null; //or return new Dictionary<string,int>();
        }
        Dictionary<string, int> tags = new Dictionary<string, int>();

        foreach (string word in words)
        {
            int count = 1;
            if (tags.ContainsKey(word))
            {
                count = tags[word] + 1;
            }

            tags[word] = count;
        }

        return tags.Select(kvp => new Tag(kvp.Key, kvp.Value));
    }

至于为什么你的“单词”参数为空,看到你试图解析的CSV文件会很有帮助。

希望这有帮助!