Recursive generic types

前端 未结 2 1405
悲&欢浪女
悲&欢浪女 2020-11-29 06:27

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).

<
2条回答
  •  Happy的楠姐
    2020-11-29 07:21

    Try:

    class StringToDictionary : Dictionary { }
    

    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.

提交回复
热议问题