为什么会发生这种嵌套对象初始化抛出一个空引用异常? [英] Why does this nested object initializer throw a null reference exception?

查看:329
本文介绍了为什么会发生这种嵌套对象初始化抛出一个空引用异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的测试用例抛出一个空引用异常,当它试图分配的ID以一个对象,它是空的,因为代码对象初始化之前缺少新的R。



这是为什么不是由编译器捕获?为什么不允许,其中使用情况这会是一个有意义的结构?



  [TestClass中] 
公共类一次性
{
公共类H
{
公众诠释标识{搞定;组; }
}

公共类R
{
公众h头{搞定;组; }
}

[TestMethod的]
公共无效ThrowsException()
{
变种要求=新R
{
头=
{
ID = 1
},
};
}
}


解决方案

的编译器不会发出警告,因为你可以有:

 公共类R 
{
公共ħ头{搞定;组; }

公共R()
{
=头新H();
}
}



所以标题可以通过某人/某物被初始化。解决如果某人/某物将初始化标题是一个复杂的问题(可能类似于停机问题)......不是一个编译器要为您解决: - )



从C#说明:




一个成员的初始值,指定后对象初始化等号是一个嵌套对象初始化,即嵌入对象的初始化。 而不是指定一个新值字段或属性,在嵌套对象初始化的任务被视为分配到外地或财产的成员。嵌套对象初始化器不能用于将属性与值类型,或者只读了值类型字段。




我们在嵌套初始化的情况下,看到粗体部分。我不知道它。



现在,请注意,新的R {} ,通过C#规范中, 7.6.10.1对象创建表达式后跟一个对象初始化,而 =标题{ } 是一个纯 7.6.10.2对象初始


The following testcase throws a null-reference exception, when it tries to assign Id to an object which is null, since the code is missing the "new R" before the object initializer.

Why is this not caught by the compiler? Why is it allowed, in which use-cases would this be a meaningful construct?

[TestClass]
public class ThrowAway
{
    public class H
    {
        public int Id { get; set; }
    }

    public class R
    {
        public H Header { get; set; }
    }

    [TestMethod]
    public void ThrowsException()
    {
        var request = new R
                      {
                          Header =
                          {
                              Id = 1
                          },
                      };
    }
}

解决方案

The compiler doesn't give a warning because you could have:

public class R
{
    public H Header { get; set; }

    public R()
    {
        Header = new H();
    }
}

so Header could be initialized by someone/something. Solving if someone/something will initialize Header is a complex problem (probably similar to the Halting problem)... Not something that a compiler wants to solve for you :-)

From the C# specifications:

A member initializer that specifies an object initializer after the equals sign is a nested object initializer, i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type.

We are in the case of nested initializer, and see the bolded part. I didn't know it.

Now, note that new R { } is, by C# spec, an 7.6.10.1 Object creation expressions followed by an object-initializer, while the Header = { } is a "pure" 7.6.10.2 Object initializers.

这篇关于为什么会发生这种嵌套对象初始化抛出一个空引用异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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