In C#, is there a way to write custom object initializers for new data-types?

前端 未结 3 1374
孤独总比滥情好
孤独总比滥情好 2021-02-09 08:43

In C#, there\'s the \"standard\" initializer technique { Property1 = \"a\", Property2 = \"b\" }, and there are a couple of special variants for collections (list and dictionary)

3条回答
  •  臣服心动
    2021-02-09 09:32

    If the nodes of your tree are easy to construct, i.e. can be initialized from their value, then you can make things terser than ChaosPandion's answer, by adding an extra method:

    class Tree : IEnumerable
    {
        public string Value { get; set; }
    
        public void Add(Tree t) { ... }
    
        // Add this method
        public void Add(string s)
        {
            Add(new Tree { Value = s });
        }
    
        public IEnumerator GetEnumerator() { ... }
    }
    

    So:

    { item1 { item2 item3 item4 } { item5 item6 } }
    

    Becomes:

    new Tree { "item1", new Tree { "item2", "item3", "item4" }, new Tree { "item5", "item6" } };
    

提交回复
热议问题