int类型必须是引用类型才能将其用作形参

本文关键字:形参 类型 引用类型 int | 更新日期: 2023-09-27 18:15:30

我有一个简单的代码,当我改变行my.Test<int>();对于my.Test<string>();,它可以工作,但是对于int不行。

class Program
{
    class MyClass
    {
        public void Test<T>()
            where T : class     // Generic Constraint
        {
            Console.WriteLine("Hello"); // Prints Hello
        }
    }
    static void Main()
    {
        MyClass my = new MyClass();
        my.Test<int>();
        Console.ReadKey();
    }
}

int类型必须是引用类型才能将其用作形参

在你的代码中有

where T : class

int不是类。