向List添加值时触发System.NullReferenceException的原因
空引用异常原因分析
你遇到的System.NullReferenceException是因为**PostUndKey类中的Id属性未被初始化**。
在C#中,引用类型(比如List<T>)的默认值是null。当你执行PostUndKey x = new PostUndKey();时,x对象的Id、von_datum、bis_datum这些List类型的属性都还是null,并没有实际创建List实例。这时候调用x.Id.Add(z),本质是在尝试对null对象调用Add方法,自然会触发空引用异常。
解决方法
- 方法一:在类的构造函数中初始化List属性
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; } public PostUndKey() { Id = new List<int>(); von_datum = new List<string>(); bis_datum = new List<string>(); } }
这样每次实例化PostUndKey对象时,所有List属性都会被自动初始化为空实例,后续调用Add方法就不会报错。
- 方法二:使用前手动初始化目标属性
PostUndKey x = new PostUndKey(); var z = 42; x.Id = new List<int>(); // 先创建List实例 x.Id.Add(z);
内容的提问来源于stack exchange,提问作者Steven Tumler
相关产品推荐
相关产品推荐

