开发者

Generics - Clarification Required

When开发者_Python百科 we declare (example) List<T> I can understand the declaration, but suppose I declare

IEnumerable<T<T1, T2>>

What did I actually declare?

  1. Does it mean, IEnumerable<T> contains two generic types? (What is the way to use it?)

  2. Can I have deep nested level like Person<T<T2<T3<P1,P2>>>>?

Simple example will really helpful.


If you have a class

public class Pair<T1, T2> { ... }

then you can declare a method

IEnumerable<Pair<int, string>> GetPairs();

i.e. a method that returns an enumerable of pairs where each pair consists of an int and a string.

Usage:

foreach (Pair<int, string> pair in GetPairs()) { ... }

You can also deeply nest these:

IEnumerable<Pair<int, Pair<string, string>>> GetPairs();

i.e. a method that returns an enumerable of pairs where each pair consists of an int and a pair of two strings.

This works with generics as well:

IEnumerable<Pair<T1, T2>> GetPairs<T1, T2>();

i.e. a method that returns an enumerable of pairs where each pair consists of a T1 and a T2.

But you cannot do this:

IEnumerable<T<T1, T2>> GetGenericPairs<T, T1, T2>();


Unless you've actually got a generic type called T, that won't work. You need a real type there, e.g.

IEnumerable<Dictionary<string, int>>

which is a sequence of Dictionary<string, int> references.

But yes, you can nest generics a lot - and it becomes pretty unreadable:

List<Dictionary<List<IEnumerable<string>>, Dictionary<int, int>>> aargh = null;


The above example will not compile. But you can embed Generic types within one another with something like this:

IEnumerable<IEnumerable<int>>

Which would be an enumerable of an enumerable of ints (which would act as a jagged 2 dimensional array).


(1) You declared an IEnumerable that enumerates objects of type T<T1, T2>. For example, Hashtable<Int, String>.

(2) Sure you can!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜