为什么具有 "where T : class" 约束的通用 <T> 方法接受接口

Why does a Generic<T> method with a "where T : class" constraint accept an interface

我有这个interface:

public interface ITestInterface
{
    int TestInt { get; set; }
}

和这个通用方法(具有 T : class 约束):

public void Test<T>() where T : class
{
    // DoSomething
}

这个电话:

Test<ITestInterface>();

一切都编译和运行,而 interface 不是 class(或者是?)。

为什么会这样?

我第一次看到这个是在我的 WCF 代理上 class:

public partial class TestServiceClient:
     System.ServiceModel.ClientBase<TestNamespace.ITestService>, TestNamespace.ITestService

其中 ClientBase<T> 具有以下定义:

public abstract class ClientBase<TChannel> : 
     ICommunicationObject, IDisposable where TChannel : class

class约束的意思是类型必须是引用类型,不一定是class.

来自 C# 语言规范:

The reference type constraint specifies that a type argument used for the type parameter must be a reference type. All class types, interface types, delegate types, array types, and type parameters known to be a reference type (as defined below) satisfy this constraint.

基本上就是说类型不能是值类型。

值类型也可以实现接口,但是将值类型转换为接口会导致值被装箱

IComparable i = 0;

现在 i 存储对盒装 0 的引用。