c# – 为什么使用“where T:class”约束的Generic方法接受一个接口

前端之家收集整理的这篇文章主要介绍了c# – 为什么使用“where T:class”约束的Generic方法接受一个接口前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个界面: @H_403_2@public interface ITestInterface { int TestInt { get; set; } }

和这种通用方法(具有T:类约束):

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

这个电话:

@H_403_2@Test<ITestInterface>();

并且所有的编译和运行,而界面不是类(或是吗?).

为什么会发生这种情况?

我第一次看到我的WCF代理类:

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

其中ClientBase< T>有这个定义:

@H_403_2@public abstract class ClientBase<TChannel> : ICommunicationObject,IDisposable where TChannel : 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.

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

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

@H_403_2@IComparable i = 0;

现在我存储一个参考的盒装0.

猜你在找的C#相关文章