gpt4 book ai didi

c# - 为什么这个带有花括号的错误对象初始化甚至可以编译?

转载 作者:行者123 更新时间:2023-11-30 14:06:16 25 4
gpt4 key购买 nike

<分区>

在为 WPF/MVVM 项目的集合创建一些虚拟数据时,我生成了以下错误代码,编译正常,但在运行时抛出异常。

有一个数据对象的嵌套结构,我错误地只用花括号实例化了它(看起来编写 JavaScript 确实会对大脑造成永久性损伤)。

using System.Collections.ObjectModel;

namespace testapp
{
class Program
{
static void Main(string[] args)
{
var collection = new ObservableCollection<TopLevelDataObject>();
collection.Add(new TopLevelDataObject{Nested = {Bar = 5}}); // NullReferenceException
}

class TopLevelDataObject
{
public NestedDataObject Nested { get; set; }
public string Foo { get; set; }
}

class NestedDataObject
{
public double Bar { get; set; }
}
}
}

为什么会编译?

如果我创建一个匿名类型,比如 Nested = new {Bar = 5},我在编译期间收到错误消息(因此失败):

Cannot implicitly convert type '<anonymous type: int Bar>' to 'testapp.Program.NestedDataObject'

为什么在省略 new 运算符时没有出现这样的错误?

它甚至为我提供了该属性的代码提示: click to see the image, for I do not have enough rep to embed it yet

我的猜测是 {Bar = 5} 只是一个代码块,它本身就是一个有效的东西。但为什么将代码块分配给任何东西(在本例中为 Nested 属性)是有效的?

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