加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:05:04 所属栏目:百科 来源:网络整理
导读:我有这个界面: public interface ITestInterface{ int TestInt { get; set; }} 和这种通用方法(具有T:类约束): public void TestT() where T : class{ // DoSomething} 这个电话: TestITestInterface(); 并且所有的编译和运行,而界面不是类(或是吗?).
我有这个界面:
public interface ITestInterface
{
    int TestInt { get; set; }
}

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

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

这个电话:

Test<ITestInterface>();

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

为什么会发生这种情况?

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

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

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

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.

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

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

IComparable i = 0;

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读