在没有“新列表”的情况下初始化列表属性。导致NullReferenceException [英] Initializing list property without "new List" causes NullReferenceException

查看:72
本文介绍了在没有“新列表”的情况下初始化列表属性。导致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" }
         }
      };
   }
}

上面的程序编译良好,但是在运行时崩溃对象引用未设置为该对象的实例

The above program compiles fine, but crashes at runtime with Object reference not set to an instance of the object.

如果您在上述代码段中注意到,我省略了新内容

If you notice in the above snippet, I have omitted new while initializing the child properties.

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

Obviously the correct way to initialize is:

      var parent = new Parent() {
         Child = new Child() {
            Strings = new List<string> { "hello", "world" }
         }
      };

我的问题是为什么C#编译器在看到第一个构造时不抱怨?

My question is why does the C# compiler not complain when it sees the first construct?

为什么初始化无效的语法无效?

Why is the broken initialization valid syntax?

      var parent = new Parent() {
         Child = {
            Strings = { "hello", "world" }
         }
      };


推荐答案

第二种语法对只读属性有效。如果更改代码以在各自的构造函数中初始化Child和Strings属性,则语法有效。

The second syntax is valid for readonly properties. If you change the code to initialise the Child and Strings properties in the respective constructors, the syntax works.

class Parent
{
    public Parent()
    {
        Child = new Child();
    }

    public Child Child { get; private set; }
}

class Child
{
    public Child()
    {
        Strings = new List<string>();
    }
    public List<string> Strings { get; private set; }
}

static class Program
{
    static void Main()
    {
        // works fine now
        var parent = new Parent
        {
            Child =
            {
                Strings = { "hello", "world" }
            }
        };

    }
}

这篇关于在没有“新列表”的情况下初始化列表属性。导致NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆