public class Program { public static void Main(string[] args) { Pair<int, string> p = new Pair<int, string>(12,"name"); Console.WriteLine(p.First+","+p.Second); Console.ReadLine(); } } public interface IPair<T1, T2> { T1 First { get; set; } T2 Second { get; set; } } public struct Pair<T1, T2> : IPair<T1, T2> { public Pair(T1 first, T2 second) : this()//结构体的构造参数需要加上这个。 { this.First = first; this.Second = second; } public T1 First { get; set; } public T2 Second { get; set; } }
上述代码就是泛型的一个例子
1.1 元数
元数是指类型参数的数量,对类进行了唯一性区分。每个泛型类型的元数都必须固定。
1.2嵌套泛型类型
避免在嵌套类型中用同名参数隐藏外层类型的类型参数。
如下代码,这时候vs编译器会给出警告,嵌套类型中对T 的任何引用都会引起嵌套的T类型参数。
public class Container<T, U> { /// <summary> /// 嵌套类 /// </summary> /// <typeparam name="U"></typeparam> public class Nested<U> { public void Method(T t, U u) { } } }