如何定义一个实现了接口,并限制了类型参数泛型类? [英] How do I define a generic class that implements an interface and constrains the type parameter?

查看:1141
本文介绍了如何定义一个实现了接口,并限制了类型参数泛型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Sample<T> : IDisposable // case A
{
    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

class SampleB<T> where T : IDisposable // case B
{
}

class SampleC<T> : IDisposable, T : IDisposable // case C
{
    public void Dispose()
    {
        throw new NotImplementedException();
    }
}



案例C是实例A和B的组合。 那可能吗?
如何使箱C吧?

Case C is the combination of case A and case B. Is that possible? How to make case C right?

推荐答案

首先实现的接口,然后泛型类型的限制由<$分开C $ C>其中,:

First the implemented interfaces, then the generic type constraints separated by where:

class SampleC<T> : IDisposable where T : IDisposable // case C
{        //                      ↑
    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

这篇关于如何定义一个实现了接口,并限制了类型参数泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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