gpt4 book ai didi

c# - 这是 C# 4.0 编译器中的错误吗?

转载 作者:可可西里 更新时间:2023-11-01 03:02:48 25 4
gpt4 key购买 nike

这段代码编译成功,但我认为它应该编译失败。此外,当您运行它时,您会得到一个 NullReferenceException。缺少的代码是 Bar 属性初始化中的“new Bar”。

class Bar
{
public string Name { get; set; }
}

class Foo
{
public Bar Bar { get; set; }
}


class Program
{
static void Main(string[] args)
{
var foo = new Foo
{
Bar = { Name = "Hello" }
};
}
}

这是一个已知错误吗?

最佳答案

为什么你认为它应该编译失败?它是嵌套的对象初始化语法,客户端代码负责为初始化提供有效值。

来自文档:

C# 规范 7.5.10.2“对象初始值设定项”

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

关于c# - 这是 C# 4.0 编译器中的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3840024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com