gpt4 book ai didi

c# - 为什么 name 在当前的速记成员初始化上下文中不存在?

转载 作者:太空狗 更新时间:2023-10-29 17:50:19 26 4
gpt4 key购买 nike

我正在为 st 对象使用对象初始值设定项:

public class Container 
{
public Container () { ContainedItem = new Item; }
public Item ContainedItem { get; set; }
}

public class Item
{
public string Value { get; set; }
}

var MyContainer = new Container()
{
// I want to populate the the property Value of the property Item
// with the second line rather than the first
ContainedItem = new Item() { Value = FooString }, // This works
ContainedItem.Value = FooString // This assigns to the same member but does not work
};

第二个初始化行给出了错误:

The name 'ContainedItem' does not exist in the current context.

Invalid initializer member declarator.

并建议在局部范围内的某处声明 ContainedItem

现在第一行可以看到 ContainedItem 实际上是 Container 的一个有效属性并且 MyContainer.ContainedItem 是绝对不是 null...那么为什么下面这行无法识别它呢?

最佳答案

内联对象初始化的语法有明确规定。您不能只是编造东西并期望编译器能够理解。语法是严格的:

{
Property1 = Value1,
Property2 = Value2,
...
}

c.x不是 st 的属性(property). c是。因此,你不能说 c.x = Bar[i].x

来自 C# 语言规范部分 7.6.10.2:


object-initializer:
<br/>
{ member-initializer-listopt }

{ member-initializer-list , }
member-initializer-list:

member-initializer

member-initializer-list , member-initializer
member-initializer:

identifier = initializer-value
initializer-value:

expression

object-or-collection-initializer

关于c# - 为什么 name 在当前的速记成员初始化上下文中不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45211600/

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