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

前端 未结 3 1366
孤独总比滥情好
孤独总比滥情好 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:23

    If you implement the ICollection IEnumerable interface and have a method called add. Incidentally, this is all included in the ICollection interface which is why I confused it.

    Test test = new Test() {
        new Test2() {
            new Test3() {
    
            }
        },
        new Test() {
            new Test2() {
                { new Test(), new Test2() },
                { new Test(), new Test2() },
                { new Test(), new Test2() }
            }
        }
    };
    
    public class Test : IEnumerable
    {
        public void Add(Test a){}
        public void Add(Test2 a){}
        public IEnumerator GetEnumerator(){}
    }
    
    public class Test2 : IEnumerable
    {
        public void Add(Test a, Test2 b){}
        public void Add(Test3 a){}
        public IEnumerator GetEnumerator(){}
    }
    
    public class Test3 : IEnumerable
    {
        public void Add(Test a) {}
        public void Add(Test2 a){}
        public IEnumerator GetEnumerator(){}
    }
    

提交回复
热议问题