How do I define a generic class that implements an interface and constrains the type parameter?
class Sample<T> : IDisposable // case A
{
public 开发者_StackOverflowvoid 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();
}
}
Case C is the combination of case A and case B. Is that possible? How to make case C right?
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();
}
}
class SampleC<T> : IDisposable where T : IDisposable // case C
{
public void Dispose()
{
throw new NotImplementedException();
}
}
You can do it like this:
public class CommonModel<T> : BaseModel<T>, IMessage where T : ModelClass
class SampleC<T> : IDisposable where T : IDisposable
{
...
}
the thing is to keep 'where ...' at the end
public class BaseRepository<TEntity> : IRepository<TEntity>, IDisposable where TEntity : class
{
// enter code here
}
精彩评论