在C#中,有没有编写自定义对象初始化新的数据类型的方法吗? [英] In C#, is there a way to write custom object initializers for new data-types?

查看:246
本文介绍了在C#中,有没有编写自定义对象初始化新的数据类型的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,有标准的初始技术{Property1 =A,Property2 =B},并有用于集合(列表和字典)一组特殊的变种。 {值1,值}和{{键1,值1},{KEY2,值2}}

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). {value1, value2}, and { {"key1", value1 }, {"key2", value2} }.

我想有一个递归对象初始化一棵树的数据类型,但我不知道是否有什么办法可以自定义机制。我想要的东西,看起来像一个s表达式。
{{ITEM1 item3的ITEM2 ITEM4} {ITEM5 ITEM6}}

I'd like to have a recursive object initializer for a tree data type, but I don't know if there's any way to customize that mechanism. I'd like something that looks like an s-expression. { item1 {item2 item3 item4 } {item5 item6} }

我通过构造这样做,但我想一个更简洁的语法。

I'm doing this via constructors, but I'd like a terser syntax.

推荐答案

如果您实施<罢工>的ICollection IEnumerable接口,并有一个方法叫加。顺便说一句,这是所有包含在ICollection接口这就是为什么我糊涂了。

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(){}
}

这篇关于在C#中,有没有编写自定义对象初始化新的数据类型的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆