A generic class includes one or more type parameters that will be substituted with actual types when the class is used. If the class has more than one type parameter, all parameters must be substituted when the class is used.
Here's an example of a generic class that stores two objects, each having its own type.
1 public class ThingContainer<TThing1, TThing2> 2 { 3 private TThing1 thing1; 4 private TThing2 thing2; 5 6 public void SetThings(TThing1 first, TThing2 second) 7 { 8 thing1 = first; 9 thing2 = second; 10 } 11 12 public string DumpThings() 13 { 14 return string.Format("{0},{1}", thing1.ToString(), thing2.ToString()); 15 } 16 }
We can use this class as follows:
1 ThingContainer<string, int> cont1 = new ThingContainer<string, int>(); 2 cont1.SetThings("Hemingway", 1899); 3 Console.WriteLine(cont1.DumpThings()); 4 5 ThingContainer<Dog, DateTime> cont2 = new ThingContainer<Dog, DateTime>(); 6 cont2.SetThings(new Dog("Kirby", 14), new DateTime(1998, 5, 1)); 7 Console.WriteLine(cont2.DumpThings());
原文地址:#324 - A Generic Class Can Have More than One Type Parameter
本文深入解析了泛型类的概念及其在实际编程中的应用,通过实例展示了如何使用具有两个类型参数的泛型类来存储不同类型的对象,并在实际场景中灵活运用。
6902

被折叠的 条评论
为什么被折叠?



