[英]How to force a class to implement a property that derives from a specific base class/interface (rather than is of a specific type)
In my solution, there are a number of classes C1
, C2
, C3
etc. that all inherit from a common abstract base class CB
. 在我的解决方案中,有许多类C1
, C2
, C3
等,它们都从通用抽象基类CB
继承。
There are also a number of classes D1
, D2
, D3
etc. that act as a data-source for the corresponding C
class (eg the data-source for C1
is a local property of type D1
etc). 还有许多类D1
, D2
, D3
等,它们充当相应C
类的数据源(例如, C1
的数据源是D1
等类型的局部属性)。 The D
classes all inherit from a common abstract base class DB
, but vary in their implementation (both inherited and non-inherited properties & methods are used by the C
class). D
类都继承自通用的抽象基类DB
,但是实现方式有所不同( C
类使用继承的和非继承的属性和方法)。
Now, I want to impose a rule that all C
classes (ie that derive from CB
) must implement a "data-source" property, and the type of this property must be derived from DB
. 现在,我想强加一个规则,即所有C
类(即从CB
派生的)都必须实现“数据源”属性,并且该属性的类型必须从DB
派生。
My initial idea was to do this: 我最初的想法是这样做:
public abstract class CB
{
protected abstract DB DataSource { get; set; }
etc.
}
However, this means that the overridden DataSource
property in the C
classes can only be of type DB
, not a type derived from DB
. 但是,这意味着C
类中重写的DataSource
属性只能是DB
类型,而不是从DB
派生的类型。
How can I impose my rule? 我该如何强加我的规则? Ideally CB
and DB
would remain abstract base classes (because there are non-abstract properties and methods in each that I wish the C
and D
classes to inherit), but they could be converted to interfaces if needed. 理想情况下, CB
和DB
将保留为抽象基类(因为我希望C
和D
类都继承非抽象的属性和方法),但是可以根据需要将它们转换为接口。 However I think I have exactly the same problem if I do that. 但是,我认为如果这样做,我会遇到完全相同的问题。
You're looking for generic class: 您正在寻找通用类:
public abstract class CB<T> where T : DB
{
protected abstract T DataSource { get; set; }
etc
}
Now, C1
should be defined as: 现在, C1
应该定义为:
public class C1 : CB<D1>
{
protected override D1 DataSource { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.