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

喜欢而已 提交于 2019-12-04 02:53:06

问题


I have this interface:

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

and this generic method (with a T : class constraint):

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

and this call:

Test<ITestInterface>();

and everything compiles and runs while an interface is not a class (or is it?).

Why does this happen?

I first saw this on my WCF proxy class:

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

where ClientBase<T> has this definition:

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

回答1:


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.



来源:https://stackoverflow.com/questions/33720381/why-does-a-generict-method-with-a-where-t-class-constraint-accept-an-inter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!