繁体   English   中英

如何定义实现接口并约束类型参数的通用 class?

[英]How do I define a generic class that implements an interface and constrains the type parameter?

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 正确?

首先是实现的接口,然后是由where分隔的泛型类型约束:

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

你可以这样做:

public class CommonModel<T> : BaseModel<T>, IMessage where T : ModelClass
class SampleC<T> : IDisposable where T : IDisposable // case C
{    
    public void Dispose()    
    {        
        throw new NotImplementedException();    
    }
}
class SampleC<T> : IDisposable where T : IDisposable
{
...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM