【问题标题】:System.NullReferenceException when i try to add a value to my List [duplicate]System.NullReferenceException 当我尝试向我的列表中添加一个值时[重复]
【发布时间】:2023-01-24 23:38:55
【问题描述】:

我有一个看起来像这样的班级。

public class PostUndKey
{
    public string Key { get; set; }
    public List<int> Id { get; set; }
    public List<string> von_datum { get; set; }
    public List<string> bis_datum { get; set; }
}

在我的代码中,我使用了这样的东西。

PostUndKey x = new PostUndKey();
var z = 42;
x.Id.Add(z);

而且我总是得到 Null Reference Exception。 有人可以向我解释一下吗,我不明白。

谢谢

【问题讨论】:

    标签: c# .net-6.0 visual-studio-2022


    【解决方案1】:

    您需要创建一个 List&lt;int&gt; 实例并将其分配给 Id 属性。 List&lt;T&gt; 是引用类型,default value 的引用类型是 null。例如:

    PostUndKey x = new PostUndKey();
    x.Id = new List<int>();
    var z = 42;
    x.Id.Add(z);
    

    或者为PostUndKey实例创建初始化Id

    public class PostUndKey
    {
        public string Key { get; set; }
        public List<int> Id { get; set; } = new List<int>();
        public List<string> von_datum { get; set; }
        public List<string> bis_datum { get; set; }
    }
    

    阅读更多:

    【讨论】:

      猜你喜欢
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多