문제

I did not see any explanation of this on MSDN:Object and Collection Initializers. Specifically, I've noted that it is possible to use an object initializer to set a property on a subType, rather than newing the sub-type itself.

The syntax itself doesn't match my understanding of the MSDN page. I understand that I can use an object initializer to set a field of an initialized object, but don't see where it is documented that it is possible to set a field of a field.

It makes sense to me that this is legal. One could accomplish the same thing with bt.subType.subTypeValue=5;.

class BasicSubType
{
    public int subTypeValue;
}

class BasicType
{
    public BasicSubType subType {get;private set;}
    public BasicType()
    {
        subType = new BasicSubType();
    }
}

void Main()
{
    BasicType bt = new BasicType{subType={subTypeValue=5}};
}
도움이 되었습니까?

해결책

I'm not sure where you'd find it in the user documentation, but it is specifically addressed in the language specification in the section on object initialisers:

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.

This text is also part of Overview of C# 3.0.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top