泛型
泛型是一种创建可重用且灵活的代码的方法,它允许您定义类、方法或数据结构,而无需在使用前指定其将使用的**确切类型**。
泛型引入了**类型参数**,它充当您稍后指定的实际数据类型的占位符。
通用类
public class Box{ private T _item; public void Add(T item) { _item = item; } public T Get() { return _item; } } --- Calling a generic class Box intBox = new Box (); intBox.Add(42); Console.WriteLine($"Int value: {intBox.Get()}"); Box stringBox = new Box (); stringBox.Add("Hello Generics!"); Console.WriteLine($"String value: {stringBox.Get()}");
通用方法
public static void PrintValues(T a, T b) { Console.WriteLine($"Value 1: {a}, Value 2: {b}"); } // Usage PrintValues(10, 20); // Output: Value 1: 10, Value 2: 20
我们也可以在泛型中使用引用类型
public static void Swap(ref T a, ref T b) { T temp = a; a = b; b = temp; } // Usage int x = 10, y = 20; Swap(ref x, ref y); // Now x = 20, y = 10
通用约束
C# 中的 **泛型约束** 是一种指定类型参数 (T) 必须满足的要求才能在泛型类、方法或委托中使用的方法。默认情况下,泛型中的类型参数可以表示任何类型。约束允许您缩小范围,确保类型参数满足特定条件。
**句法**
public class MyClasswhere T : constraint { // Class implementation }
例子
where T : struct (Value Type Constraint) Restricts T to value types like int, float, bool, etc. We cannot directly assign the dateType in the contraint.(for eg . where T:int) public class ValueContainerwhere T : struct { public T Value { get; set; } } // Usage ValueContainer intContainer = new ValueContainer (); // ValueContainer stringContainer; // Compilation error
where T : class (Reference Type Constraint) Restricts T to reference types like string, classes, or interfaces. public class ReferenceContainerwhere T : class { public T Value { get; set; } } // Usage ReferenceContainer stringContainer = new ReferenceContainer (); // ReferenceContainer intContainer; // Compilation error
You can combine multiple constraints using a comma-separated list. public class MultiConstraintwhere T : class, new() { public T CreateInstance() { return new T(); } }