泛型,泛型约束

什么是泛型?

泛型(Generics) 是一种编程技术,广泛应用于面向对象编程(OOP)中,特别是在C#、Java等现代编程语言中。泛型的核心思想是创建可以在多种数据类型上工作的类、接口和方法,而不需要为每种数据类型单独编写代码。这不仅提高了代码的重用性,还增强了类型安全性,减少了运行时错误。

泛型的主要优点

  1. 类型安全性:
    • 泛型在编译时进行类型检查,确保类型的一致性,减少运行时类型转换错误。
  2. 代码重用:
    • 通过泛型,可以编写适用于多种数据类型的通用代码,而不需要为每种数据类型编写单独的实现。
  3. 性能提升:
    • 泛型避免了装箱(boxing)和拆箱(unboxing)操作,提高了性能,特别是在处理值类型时。
  4. 可读性和可维护性:
    • 泛型代码更易于阅读和维护,因为类型信息在编译时就已经明确。

泛型的实现

  1. 泛型类:
    定义一个类,使其可以处理多种数据类型的实例。

    public class Box
    {
    private T _content;

    public void SetContent(T content)
    {
    _content = content;
    }

    public T GetContent()
    {
    return _content;
    }
    }

    public class Program
    {
    public static void Main()
    {
    Box intBox = new Box();
    intBox.SetContent(42);
    Console.WriteLine(intBox.GetContent()); // 输出: 42

    Box stringBox = new Box();
    stringBox.SetContent("Hello, World!");
    Console.WriteLine(stringBox.GetContent()); // 输出: Hello, World!
    }
    }

  2. 泛型接口:
    定义一个接口,使其可以处理多种数据类型的实例。

    public interface IStorage
    {
    void Store(T item);
    T Retrieve();
    }

    public class Storage : IStorage
    {
    private T _item;

    public void Store(T item)
    {
    _item = item;
    }

    public T Retrieve()
    {
    return _item;
    }
    }

    public class Program
    {
    public static void Main()
    {
    IStorage intStorage = new Storage();
    intStorage.Store(100);
    Console.WriteLine(intStorage.Retrieve()); // 输出: 100

    IStorage stringStorage = new Storage();
    stringStorage.Store("Generic Storage");
    Console.WriteLine(stringStorage.Retrieve()); // 输出: Generic Storage
    }
    }

  3. 泛型方法:
    定义一个方法,使其可以处理多种数据类型的参数和返回值。

    public class GenericMethods
    {
    public static T GetDefault() where T : new()
    {
    return new T();
    }

    public static void Print(T item)
    {
    Console.WriteLine(item);
    }
    }

    public class Program
    {
    public static void Main()
    {
    int defaultInt = GenericMethods.GetDefault();
    Console.WriteLine(defaultInt); // 输出: 0

    string defaultString = GenericMethods.GetDefault();
    Console.WriteLine(defaultString); // 输出: (空字符串)

    GenericMethods.Print(42); // 输出: 42
    GenericMethods.Print("Hello, World!"); // 输出: Hello, World!
    }
    }

  4. 泛型约束:
    可以为泛型类、接口和方法添加约束,以限制泛型参数的类型。
    常见的约束包括:

    • where T : new():要求泛型参数必须有一个无参构造函数。

    • where T : class:要求泛型参数必须是引用类型。

    • where T : struct:要求泛型参数必须是值类型。

    • where T : IInterface:要求泛型参数必须实现特定的接口。

    • where T : BaseClass:要求泛型参数必须继承自特定的基类。

      public class GenericConstraint 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 constraint = new GenericConstraint();
      MyClass instance = constraint.CreateInstance();
      instance.MyMethod(); // 输出: MyClass instance created.
      }
      }

  5. 泛型的应用场景
    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
{
private List _elements = new List();

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 intStack = new Stack();
intStack.Push(1);
intStack.Push(2);
Console.WriteLine(intStack.Pop()); // 输出: 2

Stack stringStack = new Stack();
stringStack.Push("Hello");
stringStack.Push("World");
Console.WriteLine(stringStack.Pop()); // 输出: World
}
}

3.工厂模式
泛型可以用于实现工厂模式,创建不同类型的对象。

public class Factory 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 productFactory = new Factory();
Product product = productFactory.Create();
product.Display(); // 输出: Product displayed.

Factory serviceFactory = new Factory();
Service service = serviceFactory.Create();
service.Execute(); // 输出: Service executed.
}
}

posted @ 2024-12-27 16:43  似梦亦非梦  阅读(231)  评论(0)    收藏  举报