无法找到这个NullReferenceException异常的原因异常、原因、NullReferenceException

2023-09-06 22:50:21 作者:抹不掉的轻狂

我有以下方法:

internal static void removeMethodFromTag(byte p, Method method)
        {
            Console.WriteLine("Remove method " + method.getName() + " from the tag");
            List<Method> outList = new List<Method>();
            methodTaggings.TryGetValue(p, out outList);
            Console.WriteLine(outList.Count);
            outList.Remove(method);
            methodTaggings.Remove(p);
            methodTaggings.Add(p, outList);
        }

这是dictionarry methodTaggings:

This is the dictionarry methodTaggings:

private static Dictionary<byte, List<Method>> methodTaggings = new Dictionary<byte, List<Method>>();

现在我总是得到一个的NullReferenceException 的行

Now I always get a NullReferenceException in the line

Console.WriteLine(outList.Count);

但我不明白为什么?即使我没有发现,在dictionnary一个值,该清单不应为空?

But I can't see why? Even if I don't find a value in the dictionnary, the list shouldn't be null?

推荐答案

如果不是这样:

internal static void removeMethodFromTag(byte p, Method method)
        {
            Console.WriteLine("Remove method " + method.getName() + " from the tag");
            List<Method> outList = new List<Method>();
            if (methodTaggings.TryGetValue(p, out outList);
            {
              Console.WriteLine(outList.Count);
              outList.Remove(method);
              methodTaggings.Remove(p);
              methodTaggings.Add(p, outList);
           }
        }