Why does a Generic method with a “where T : class” constraint accept an interface

后端 未结 1 545
误落风尘
误落风尘 2021-01-17 11:45

I have this interface:

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

and this generic method (with a

1条回答
  •  再見小時候
    2021-01-17 12:00

    The class constraint means that the type must be a reference type, not necessarily a class.

    From C# language specification:

    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.

    Basically, it means that the type cannot be a value type.

    Value types can implement interfaces too, but casting a value type to an interface causes the value to be boxed

    IComparable i = 0;
    

    Now i stores a reference to a boxed 0.

    0 讨论(0)
提交回复
热议问题