C#对象初始化错误? [英] C# object initialization bug?

查看:129
本文介绍了C#对象初始化错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 使用系统; 
使用System.Collections.Generic;

级父
{
公共儿童儿童{搞定;组; }
}

类儿童
{
公开名单<串GT;字符串{搞定;组; }
}

静态类节目
{
静态无效的主要(){
//不好对象的初始化
变种父=新的父(){
=儿童{
弦乐= {你好,世界}
}
};
}
}



以上程序编译罚款,但与运行时崩溃对象引用未设置为



如果您在上面的代码中发现,我的忽略新的对象的实例在初始化子属性。



显然初始化正确的做法是:

  VAR父=新的父(){
=儿童新的儿童(){
弦乐=新的List<串GT; {你好,世界}
}
};



我的问题是当它看到第一个构建,为什么不抱怨C#编译器?



为什么坏了初始化有效的语法?

  VAR父=新的父() {
=儿童{
弦乐= {你好,世界}
}
};


解决方案

第二个语法是有效的只读属性。如果你改变了代码初始化在各自的构造函数的语法著作儿童和字符串属性。

 类父
{
公共父()
{
=儿童新的儿童();
}

公共儿童儿童{搞定;私人集; }
}

类儿童
{
公共儿童()
{
串=新的List<串>();
}
公开名单<串GT;字符串{搞定;私人集; }
}

静态类节目
{
静态无效的主要()
{
//工作正常,现在
变种父=新的父
{
=儿童
{
弦乐= {你好,世界}
}
};

}
}


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" }
         }
      };

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" }
         }
      };

解决方案

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" }
            }
        };

    }
}

这篇关于C#对象初始化错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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