在实现自定义栈时,我遇到了这样的错误:类型 'int' 必须是引用类型,才能在泛型类型或方法 'Stack' 中用作参数 'T'

编程语言 2026-07-11

在自己实现栈的过程中,我遇到了这个错误。

以下是我的代码

interface IStack<T> where T : class
{
    void Push(T item);
    T Pop();
    T Peek();
    bool IsEmpty { get; }
    int Count { get; }
    void Print();
}

class Stack<T> : IStack<T> where T : class
{
    private readonly List<T> _items = new();

    public void Push(T item)
    {
        _items.Add(item);
        Console.WriteLine($"Pushed {item} onto the stack.");
    }

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

        var item = _items.Last();
        _items.RemoveAt(_items.Count - 1);
        Console.WriteLine($"Popped {item} from the stack.");
        return item;
    }

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

        return _items.Last();
    }

    public bool IsEmpty => _items.Count == 0;

    public int Count => _items.Count;

    public void Print()
    {
        Console.WriteLine("Stack contents:");
        foreach (var item in _items.AsEnumerable().Reverse())
        {
            Console.WriteLine(item);
        }
    }
}

class Program
{
    static void Main()
    {
        IStack<int> intStack = new Stack<int>();
        intStack.Push(1);
        intStack.Push(2);
        intStack.Print();
        Console.WriteLine($"Top item: {intStack.Peek()}");
        Console.WriteLine($"Popped item: {intStack.Pop()}");
        Console.WriteLine($"Is stack empty? {intStack.IsEmpty}");

        IStack<string> stringStack = new Stack<string>();
        stringStack.Push("Hello");
        stringStack.Push("World");
        stringStack.Print();
        Console.WriteLine($"Top item: {stringStack.Peek()}");
        Console.WriteLine($"Popped item: {stringStack.Pop()}");
        Console.WriteLine($"Is stack empty? {stringStack.IsEmpty}");
    }
}

此时我正在学习C#的泛型,并且最近研究了Repository模式。下面是我要实现的任务(栈数据结构)

从头开始构建一个通用的 Stack<T> 数据结构——不是内置的,而是你自己的:

  • Stack<T> 类,内部存储使用私有的 List<T>
  • Push(T item) — 将项添加到顶部
  • Pop() — 移除并返回顶部的项。如果栈为空则抛出 InvalidOperationException("Stack is empty.")
  • Peek() — 返回顶部的项但不移除。若为空,抛出相同的异常。
  • IsEmpty — 布尔属性
  • Count — 整型属性
  • void PrintAll() — 从顶部到底部打印所有项

添加一个约束:where T : notnull — T不能是可空类型。

Stack<int>Stack<string> 进行测试。尝试从空栈弹出并捕获异常。

有人能告诉我这个错误是什么以及如何解决吗?

解决方案

In c# there are reference types and value types.

Classes, as well as records are reference types. While structs, record struct, as well as the built in simple numeric types like int are all value types. See built in types for details.

The where T : class in your code specifies that the generic type has to be a reference type. int is a value type, so will fail the condition. Simply replace the where T : class with where T : notnull to get rid of the error. The notnull constraints allow both value types, since they can never be null, as well as "non nullable reference types". Read more about generic constraints.

It is arguably a bit confusing that the generic constraint uses class to specify a reference type. It might have been better with something like where T : reference, but it is not really feasible to change.

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章