时间:2024-12-27 16:43
人气:
作者:admin
泛型(Generics) 是一种编程技术,广泛应用于面向对象编程(OOP)中,特别是在C#、Java等现代编程语言中。泛型的核心思想是创建可以在多种数据类型上工作的类、接口和方法,而不需要为每种数据类型单独编写代码。这不仅提高了代码的重用性,还增强了类型安全性,减少了运行时错误。
泛型的主要优点
泛型的实现
泛型类:
定义一个类,使其可以处理多种数据类型的实例。
public class Box<T>
{
private T _content;
public void SetContent(T content)
{
_content = content;
}
public T GetContent()
{
return _content;
}
}
public class Program
{
public static void Main()
{
Box<int> intBox = new Box<int>();
intBox.SetContent(42);
Console.WriteLine(intBox.GetContent()); // 输出: 42
Box<string> stringBox = new Box<string>();
stringBox.SetContent("Hello, World!");
Console.WriteLine(stringBox.GetContent()); // 输出: Hello, World!
}
}
泛型接口:
定义一个接口,使其可以处理多种数据类型的实例。
public interface IStorage<T>
{
void Store(T item);
T Retrieve();
}
public class Storage<T> : IStorage<T>
{
private T _item;
public void Store(T item)
{
_item = item;
}
public T Retrieve()
{
return _item;
}
}
public class Program
{
public static void Main()
{
IStorage<int> intStorage = new Storage<int>();
intStorage.Store(100);
Console.WriteLine(intStorage.Retrieve()); // 输出: 100
IStorage<string> stringStorage = new Storage<string>();
stringStorage.Store("Generic Storage");
Console.WriteLine(stringStorage.Retrieve()); // 输出: Generic Storage
}
}
泛型方法:
定义一个方法,使其可以处理多种数据类型的参数和返回值。
public class GenericMethods
{
public static T GetDefault<T>() where T : new()
{
return new T();
}
public static void Print<T>(T item)
{
Console.WriteLine(item);
}
}
public class Program
{
public static void Main()
{
int defaultInt = GenericMethods.GetDefault<int>();
Console.WriteLine(defaultInt); // 输出: 0
string defaultString = GenericMethods.GetDefault<string>();
Console.WriteLine(defaultString); // 输出: (空字符串)
GenericMethods.Print(42); // 输出: 42
GenericMethods.Print("Hello, World!"); // 输出: Hello, World!
}
}
泛型约束:
可以为泛型类、接口和方法添加约束,以限制泛型参数的类型。
常见的约束包括:
where T : new():要求泛型参数必须有一个无参构造函数。
where T : class:要求泛型参数必须是引用类型。
where T : struct:要求泛型参数必须是值类型。
where T : IInterface:要求泛型参数必须实现特定的接口。
where T : BaseClass:要求泛型参数必须继承自特定的基类。
public class GenericConstraint<T> where T : new()
{
public T CreateInstance()
{
return new T();
}
}
public class MyClass
{
public void MyMethod()
{
Console.WriteLine("MyClass instance created.");
}
}
public class Program
{
public static void Main()
{
GenericConstraint<MyClass> constraint = new GenericConstraint<MyClass>();
MyClass instance = constraint.CreateInstance();
instance.MyMethod(); // 输出: MyClass instance created.
}
}
泛型的应用场景
1.集合类:
泛型集合类(如List<T 、Dictionary<TKey, TValue)提供了类型安全的集合操作。
List <int numbers = new List <int();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
foreach (int number in numbers)
{
Console.WriteLine(number); // 输出: 1 2 3
}
2.算法和数据结构:
算法和数据结构:
public class Stack<T>
{
private List<T> _elements = new List<T>();
public void Push(T item)
{
_elements.Add(item);
}
public T Pop()
{
if (_elements.Count == 0)
{
throw new InvalidOperationException("Stack is empty.");
}
T item = _elements[_elements.Count - 1];
_elements.RemoveAt(_elements.Count - 1);
return item;
}
public T Peek()
{
if (_elements.Count == 0)
{
throw new InvalidOperationException("Stack is empty.");
}
return _elements[_elements.Count - 1];
}
}
public class Program
{
public static void Main()
{
Stack<int> intStack = new Stack<int>();
intStack.Push(1);
intStack.Push(2);
Console.WriteLine(intStack.Pop()); // 输出: 2
Stack<string> stringStack = new Stack<string>();
stringStack.Push("Hello");
stringStack.Push("World");
Console.WriteLine(stringStack.Pop()); // 输出: World
}
}
3.工厂模式
泛型可以用于实现工厂模式,创建不同类型的对象。
public class Factory<T> where T : new()
{
public T Create()
{
return new T();
}
}
public class Product
{
public void Display()
{
Console.WriteLine("Product displayed.");
}
}
public class Service
{
public void Execute()
{
Console.WriteLine("Service executed.");
}
}
public class Program
{
public static void Main()
{
Factory<Product> productFactory = new Factory<Product>();
Product product = productFactory.Create();
product.Display(); // 输出: Product displayed.
Factory<Service> serviceFactory = new Factory<Service>();
Service service = serviceFactory.Create();
service.Execute(); // 输出: Service executed.
}
}
上一篇:多线程的实现原理
下一篇:什么是IOC和AOP?