[英]C# NullReferenceException was unhandled
I am trying to use a CSV parser which I found on the net in my project. 我正在尝试使用我在项目中在网上找到的CSV解析器。 The problem is I am getting a null reference exception when I try to convert the string to a Tag and my collection does not get populated.
问题是当我尝试将字符串转换为Tag并且我的集合没有填充时,我得到一个空引用异常。 Can anyone assist?
有人可以帮忙吗? Thanks
谢谢
CSV Parser 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;
}
Tag Class 标签类
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));
}
}
Validate all method arguments before you use them! 在使用它们之前验证所有方法参数!
It breaks on this line: foreach (string word in words)
它打破了这一行:foreach(字中的字符串)
Remember that foreach
loops work by calling GetEnumerator
on the collection iterated over. 请记住,
foreach
循环通过在迭代的集合上调用GetEnumerator
来工作。 That is, your foreach
loop causes a call to words.GetEnumerator
, and this call fails if words
is null. 也就是说,你的
foreach
循环会调用words.GetEnumerator
,如果words
为null,则此调用将失败。
Therefore, validate your argument words
by adding a guard at the very start of your CreateTags
method: 因此,通过在
CreateTags
方法的最开头添加一个保护来验证您的参数words
:
if (words == null)
{
throw new ArgumentNullException("words");
}
This will help you find the location in your code where null
is passed into CreateTags
, and you can then continue fixing the calling code. 这将帮助您在代码中找到将
null
传递到CreateTags
,然后您可以继续修复调用代码。
Suggestion: Avoid null
whenever possible. 建议:尽可能避免使用
null
。
As a very general rule, try to avoid using null
values whenever possible. 作为一般规则,尽量避免使用
null
值。 For example, when your code is dealing with sets and collections of items, you could make sure that it also works correctly with empty collections. 例如,当您的代码处理项目的集合和集合时,您可以确保它也可以正确处理空集合。 In a second step, make sure that you never use
null
to represent an empty collection; 在第二步中,确保永远不要使用
null
来表示空集合; instead, use eg LINQ's Enumerable.Empty<TItem>()
generator to create an empty collection. 相反,使用例如LINQ的
Enumerable.Empty<TItem>()
生成器来创建一个空集合。
One place where you could start doing this is in the CreateTags
method by ensuring that no matter what the inputs are, that method will always return a valid, non-null (but possibly empty) collection: 你可以开始这样做的地方是在
CreateTags
方法中,通过确保无论输入是什么,该方法总是返回一个有效的,非空(但可能是空的)集合:
if (words == null)
{
return Enumerable.Empty<Tag>(); // You could do without LINQ by writing:
// return new Tag[] { };
}
Every method should run sanity checks on the arguments it accepts to ensure the arguments are valid input parameters. 每个方法都应该对它接受的参数进行健全性检查,以确保参数是有效的输入参数。 I would probably do something like
我可能会做类似的事情
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));
}
As to why your "words" param is null, it would be helpful to see the CSV file you are trying to parse in. 至于为什么你的“单词”参数为null,看到你试图解析的CSV文件会很有帮助。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.