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

use*_*070 1 c#

我有一个简单的代码,当我将行更改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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mac*_*akM 5

在你的代码中你有

where T : class
Run Code Online (Sandbox Code Playgroud)

而且 int 不是一个类。这就是为什么它不起作用。