Setting a read-only property with an anonymous type

I recently came up with something rather puzzled in C #. In our code base we have a class TreeNode. When changing the code, I found that it was not possible to assign a variable to a property Nodes. Upon closer inspection, it became clear that the property is read-only, and this behavior should be expected.

What is strange is that our code base has always relied on assigning some anonymous type to a property Nodesand compiled and worked perfectly.

To summarize: why is appointment AddSomeNodesin the first place?

using System.Collections.Generic;

namespace ReadOnlyProperty
{
    public class TreeNode
    {
        private readonly IList<TreeNode> _nodes = new List<TreeNode>();

        public IList<TreeNode> Nodes
        {
            get { return _nodes;  }
        }
    }

    public class TreeBuilder
    {
        public IEnumerable<TreeNode> AddSomeNodes()
        {
            yield return new TreeNode
             {
                Nodes = { new TreeNode() }
             };
        }

        public IEnumerable<TreeNode> AddSomeOtherNodes()
        {
            var someNodes = new List<TreeNode>();

            yield return new TreeNode
             {
                Nodes = someNodes
             };
        }
    }
}
+5
source share
5 answers

AddSomeNodes List<TreeNode>, ( Nodes, , readonly), .Add.

AddSomeOtherNodes , readonly. , . , . , readonly, , readonly.

MSDN:

, Add ; .

, , no - .

</" > , .

, Nodes = { new TreeNode() } , , :

List<int> numbers = { 1, 2, 3, 4 }; // This isn't valid.
List<int> numbers = new List<int> { 1, 2, 3, 4 }; // Valid.

// This is valid, but will NullReferenceException on Numbers
// if NumberContainer doesn't "new" the list internally.
var container = new NumberContainer()  
{
    Numbers = { 1, 2, 3, 4 }
};

MSDN .

+4

.

:

CollectionProperty = { a, b, c };

:

CollectionProperty.Add(a);
CollectionProperty.Add(b);
CollectionProperty.Add(c);
+2

, ICollection

 Nodes = {new TreeNode() }, that is why it works.
+1

( AddSomeOtherNodes) Reflector, :

public IEnumerable<TreeNode> AddSomeNodes()
{
    TreeNode iteratorVariable0 = new TreeNode();
    iteratorVariable0.Nodes.Add(new TreeNode());
    yield return iteratorVariable0;
}

, Add Nodes.

+1

, , :

public IEnumerable<TreeNode> AddSomeNodes()
{
    TreeNode node = new TreeNode();
    node.Nodes.Add(new TreeNode());

    yield return node;
}

The important difference here is that they used the collection initializer syntax to assign the value.

0
source

All Articles