【问题标题】:How can I be getting a NullReferenceException when using a type, not an object? [duplicate]使用类型而不是对象时如何获得 NullReferenceException? [复制]
【发布时间】:2019-01-18 08:00:44
【问题描述】:

我在以下调用中收到NullReferenceException(“对象引用未设置为对象的实例”):

XmlSerializer SerializerObj = new XmlSerializer(typeof(FooBar));

这里是Foobar

class FooBar
{
    public int Alpha{ get; set; }
    public string[] Bravo{ get; set; }
    public int[] Charlie{ get; set; }    
    public List<int> Delta{ get; set; }
    //public List<int>[] Echo { get; set; }
}

有问题的行被注释掉了。取消注释它,我在运行时收到错误。左评论没有错误。 XmlSerializer 喜欢 int、int 数组、字符串数组和 int 列表,但似乎对 int 列表数组犹豫不决。任何想法为什么和/或解决方法?

注意:我的愤世嫉俗者知道有人会试图站出来说“你还没有初始化任何属性。这就是 null 异常的原因。”在实际程序中,它们初始化。但是它们中的任何一个是否已初始化都没有关系,因为我使用的是typeof,而不是实例。

注意 2:我这个经验丰富的程序员正在嗅到一个 bug。

【问题讨论】:

  • 如果您能提供minimal reproducible example,那就太好了。该代码(甚至 with 注释掉的行)抛出异常 - 但不是您声称的异常。
  • stackoverflow.com/questions/26202994/… 可能值得一读。通过谷歌搜索找到xmlserialiser array of list nullreferenceexception
  • 来自this answer 看起来这是序列化程序中的错误。
  • 这里的回复几乎证实了我的怀疑(库错误)并提出了解决方法。一位同事建议 List> 就像 Merhat Pandzharov 在下面所做的那样。

标签: c# xml exception xmlserializer


【解决方案1】:

试试这个:

public class FooBar
{
    public int Alpha { get; set; }
    public string[] Bravo { get; set; }
    public int[] Charlie { get; set; }
    public List<int> Delta { get; set; }
    public List<List<int>> Echo { get; set; }
}

【讨论】:

  • 我回家后会试一试。列表数组会导致异常。遗憾的是,显然 MS 已经知道它至少 4 年了。
猜你喜欢
  • 2023-01-20
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 2016-04-19
  • 2023-04-09
  • 2010-09-20
相关资源
最近更新 更多