C#泛型編程如何實(shí)現(xiàn)

c#
小樊
81
2024-10-24 13:15:27
欄目: 編程語言

在C#中,泛型編程是一種編程范式,它允許程序員編寫可重用、可擴(kuò)展的代碼。泛型允許程序員創(chuàng)建能夠處理不同類型數(shù)據(jù)的類、接口和方法,而無需為每種數(shù)據(jù)類型編寫單獨(dú)的代碼。泛型編程通過類型參數(shù)來實(shí)現(xiàn),這些類型參數(shù)可以在類、接口和方法的定義中使用。

以下是使用C#泛型編程實(shí)現(xiàn)的一個(gè)簡(jiǎn)單示例:

  1. 定義一個(gè)泛型接口:
public interface IStack<T>
{
    void Push(T item);
    T Pop();
    bool IsEmpty();
}

在這個(gè)例子中,IStack<T> 是一個(gè)泛型接口,它表示一個(gè)棧數(shù)據(jù)結(jié)構(gòu)。T 是一個(gè)類型參數(shù),表示棧中存儲(chǔ)的元素類型。

  1. 實(shí)現(xiàn)泛型接口:
public class Stack<T> : IStack<T>
{
    private List<T> _items = new List<T>();

    public void Push(T item)
    {
        _items.Add(item);
    }

    public T Pop()
    {
        if (IsEmpty())
        {
            throw new InvalidOperationException("Stack is empty.");
        }

        T item = _items[_items.Count - 1];
        _items.RemoveAt(_items.Count - 1);
        return item;
    }

    public bool IsEmpty()
    {
        return !_items.Any();
    }
}

在這個(gè)例子中,Stack<T> 是一個(gè)泛型類,它實(shí)現(xiàn)了 IStack<T> 接口。_items 是一個(gè)類型為 List<T> 的私有字段,用于存儲(chǔ)棧中的元素。

  1. 使用泛型類:
public class Program
{
    public static void Main()
    {
        IStack<int> intStack = new Stack<int>();
        intStack.Push(1);
        intStack.Push(2);
        intStack.Push(3);

        Console.WriteLine("Int stack:");
        while (!intStack.IsEmpty())
        {
            Console.WriteLine(intStack.Pop());
        }

        IStack<string> stringStack = new Stack<string>();
        stringStack.Push("A");
        stringStack.Push("B");
        stringStack.Push("C");

        Console.WriteLine("\nString stack:");
        while (!stringStack.IsEmpty())
        {
            Console.WriteLine(stringStack.Pop());
        }
    }
}

在這個(gè)例子中,我們創(chuàng)建了兩個(gè)不同類型的棧:一個(gè)用于存儲(chǔ)整數(shù),另一個(gè)用于存儲(chǔ)字符串。通過使用泛型類 Stack<T>,我們可以輕松地實(shí)現(xiàn)這一目標(biāo),而無需為每種數(shù)據(jù)類型編寫單獨(dú)的代碼。

0