为什么泛型T带有“其中T:类”的方法。约束接受接口 [英] Why does a Generic<T> method with a "where T : class" constraint accept an interface

查看:77
本文介绍了为什么泛型T带有“其中T:类”的方法。约束接受接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个接口

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

和这种通用方法(使用 T: class 约束):

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

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

且此调用:

Test<ITestInterface>();

一切都会在界面下编译并运行不是一个(或者是?)。

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

为什么会这样?

我首先在WCF代理类上看到了这一点:

I first saw this on my WCF proxy 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 约束意味着该类型必须是引用类型,而不一定是类。

The class constraint means that the type must be a reference type, not necessarily a 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.

基本上,这意味着类型不能是值类型。

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;

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

Now i stores a reference to a boxed 0.

这篇关于为什么泛型T带有“其中T:类”的方法。约束接受接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆