C#泛型可以让我们编写可重用的代码,不需要为每种数据类型都写一份代码,可以通过在代码中使用类型参数来实现代码的泛化。下面是一些C#泛型的用法和示例代码:
使用关键字class来定义一个泛型类,用尖括号<>来指定类型参数。
//定义类 public class MyList<T> { private T[] array; public MyList() { array = new T[0]; } public void Add(T item) { Array.Resize(ref array, array.Length + 1); array[array.Length - 1] = item; } public T this[int index] { get { return array[index]; } set { array[index] = value; } } } //使用类 new MyList<类>().Add(类);
使用尖括号<>来指定类型参数,然后就可以在方法中使用这个类型参数。
public static T Max<T>(T x, T y) where T : IComparable<T> { if (x.CompareTo(y) > 0) { return x; } else { return y; } }
在这个例子中,where T : IComparable<T>表示泛型类型参数T必须实现IComparable<T>接口。
泛型约束可以让我们对类型参数进行限制,以确保泛型类型满足一定的条件。
public class MyClass<T> where T : class { // ... }
在这个例子中,where T : class表示泛型类型参数T必须是引用类型。
泛型接口是指具有一个或多个泛型类型参数的接口。
public interface IMyInterface<T> { T GetResult(); }
泛型委托是指一个具有泛型类型参数的委托类型。
public delegate void MyDelegate<T>(T arg);
这是一些C#泛型的用法和示例代码,希望能对你有所帮助。
2016 © donet5.comApache Licence 2.0