gpt4 book ai didi

c# - 新的 C# 6 对象初始值设定项语法?

转载 作者:太空狗 更新时间:2023-10-29 19:56:58 24 4
gpt4 key购买 nike

我只是注意到在 Visual Studio 2015 中编写的 C# 中可以实现以下内容,但我以前从未见过:

public class X
{
public int A { get; set; }

public Y B { get; set; }
}

public class Y
{
public int C {get; set; }
}

public void Foo()
{
var x = new X { A = 1, B = { C = 3 } };
}

我的期望是 Foo 必须像这样实现:

public void Foo()
{
var x = new X { A = 1, B = new Y { C = 3 } };
}

请注意,无需调用 new Y

这是 C# 6 中的新功能吗?我在 release notes 中没有看到任何提及。 ,所以也许它一直都在那里?

最佳答案

如果您运行这段代码,您将得到一个 NullReferenceException。

它不会创建Y 的实例,它会调用X.B 属性的getter 并尝试为属性C 赋值。

一直都是这样。根据 C# 5.0 语言规范:

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# 6 对象初始值设定项语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32897655/

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