.NET allows you to specify a generic type as the type of another generic type:public class Type1<T> {} public class Type2<T> {}
Type1<Type2<int>> obj = new Type1<Type2<int>>();
Simple Example
Consider a simple reference class that might be used for lazy-fetching an object. For simplicity, the lazy-fetching code has been removed:It’s possible to store this generic type Ref<T> in a List<T>, which is also a generic type.
public class Ref<T> { public Ref() { } public Ref( T val ) { this.Value = val; } public T Value; public override string ToString() { return this.Value.ToString(); } }
Here’s a sample console program to demonstrate this:
As you would expect, the console output is:static void Main( string[] args ) { List<Ref<int>> refIntList = new List<Ref<int>>(); refIntList.Add( new Ref<int>( 6 ) ); refIntList.Add( new Ref<int>( 7 ) ); foreach (Ref<int> refInt in refIntList) { Console.WriteLine( refInt ); } List<Ref<string>> refStringList = new List<Ref<string>>(); refStringList.Add( new Ref<string>( "six" ) ); refStringList.Add( new Ref<string>( "seven" ) ); foreach (Ref<string> refString in refStringList) { Console.WriteLine( refString ); } Console.ReadLine(); }
6
7
six
seven
No comments:
Post a Comment