简体   繁体   English

这两种继承之间有什么区别?

[英]What the difference between these two types of inheritance?

I'm coding a repository and i was with the following problem: 我正在编码存储库,但遇到以下问题:

The code below shows an error as if the repository were inheriting the IRepository interface and type T was inheriting IDisposable 下面的代码显示错误,好像存储库正在继承IRepository接口,类型T在继承IDisposable

public class GenericRepository<T> : IGenericRepository<T> where T : class, IDisposable

So, when i changed the inheritance order, the problem was solved 因此,当我更改继承顺序时,问题就解决了

public class GenericRepository<T> : IDisposable, IGenericRepository<T> where T : class

My solution for this problem its correct? 我对这个问题的解决方法正确吗?

In your first code snippet the IDisposable is part of the constraint. 在您的第一个代码段中, IDisposable是约束的一部分。

In your second code snippet, the IDisposable is an interface that your GenericRepository<T> implements. 在第二个代码段中, IDisposableGenericRepository<T>实现的接口。

public class GenericRepository<T> : IGenericRepository<T> where T : class, IDisposable

constrains type parameter T to implement IDisposable . 约束类型参数T以实现IDisposable

With the second code you show, it is the GenericRepository<T> which is required to implement IDisposable interface, no matter of what T is. 在第二个代码中,无论T是多少, 实现 IDisposable接口都需要GenericRepository<T>

The former: 前者:

public class GenericRepository<T> : IGenericRepository<T> where T : class, IDisposable

enforces the IDisposable constraint on type T , whereas: 对类型T强制执行IDisposable约束,而:

public class GenericRepository<T> : IDisposable, IGenericRepository<T> where T : class

requires GenericRepository<T> to implement IDisposable . 需要GenericRepository<T>来实现IDisposable

It's up to you to decide how you want to design your repositories - I'd opt for the latter. 由您决定要如何设计存储库-我会选择后者。 I'd argue its the repository's responsibility to dispose of its' resources. 我认为存储库有责任处置其资源。

Well, your first line explicitly says that T must be IDisposable. 好吧,您的第一行明确表示T必须是IDisposable。

Second line says that your GenericRepository must be IDisposable. 第二行说您的GenericRepository必须是IDisposable。 If that is your intention - yes, your solution is correct. 如果这是您的意图-是的,您的解决方案是正确的。

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

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