递归泛型类型 [英] Recursive generic types

查看:220
本文介绍了递归泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时可以定义在C#泛型类型引用本身?

例如。我想定义一个字典<>持有其类型为TValue(一层次)

 词典<字符串,字典<字符串,字典<字符串[...]>>>


解决方案

尝试:

 类StringToDictionary:字典<字符串,StringToDictionary> {}

然后,你可以写:

  VAR东西=新StringToDictionary
        {
            {果,新StringToDictionary
                {
                    {苹果,空},
                    {香蕉,NULL},
                    {柠檬,新StringToDictionary {{夏普,NULL}}}
                }
            },
        };

递归的一般原则:找到某种方式来给一个名称递归模式,因此它可以通过名字引用本身

Is it possible to define a generic type in C# that references itself?

E.g. I want to define a Dictionary<> that holds its type as TValue (for a hierarchy).

Dictionary<string, Dictionary<string, Dictionary<string, [...]>>>

解决方案

Try:

class StringToDictionary : Dictionary<string, StringToDictionary> { }

Then you can write:

var stuff = new StringToDictionary
        {
            { "Fruit", new StringToDictionary
                {
                    { "Apple", null },
                    { "Banana", null },
                    { "Lemon", new StringToDictionary { { "Sharp", null } } }
                }
            },
        };

General principle for recursion: find some way to give a name to the recursive pattern, so it can refer to itself by name.

这篇关于递归泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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