小编Aja*_*jai的帖子

初始化没有"新列表"的列表属性会导致NullReferenceException

using System;
using System.Collections.Generic;

class Parent
{
   public Child Child { get; set; }
}

class Child
{
   public List<string> Strings { get; set; }
}

static class Program
{
   static void Main() {
      // bad object initialization
      var parent = new Parent() {
         Child = {
            Strings = { "hello", "world" }
         }
      };
   }
}
Run Code Online (Sandbox Code Playgroud)

上面的程序编译很好,但在运行时崩溃,而Object引用没有设置为对象的实例.

如果您在上面的代码段中注意到,我在初始化子属性时省略了new.

显然,正确的初始化方法是:

      var parent = new Parent() {
         Child = new Child() {
            Strings = new List<string> { …
Run Code Online (Sandbox Code Playgroud)

c# nullreferenceexception

22
推荐指数
4
解决办法
2078
查看次数

标签 统计

c# ×1

nullreferenceexception ×1