[英]How do I declare an array of any type (derived from a given type) in an abstract class?
I'm not sure what the correct English words are for my problem, so I think it's best to illustrate it in code. 我不确定我的问题是什么正确的英语单词,所以我认为最好在代码中说明它。 I have a basic, abstract Windows Forms class that I use to create many derived Windows Forms that serve similar purposes.
我有一个基本的,抽象的Windows窗体类,我用它来创建许多用于类似目的的派生Windows窗体。 In the abstract base class, which we'll call
Alfred
, I have an array of type Buddy
. 在抽象基类中,我们称之为
Alfred
,我有一个类型为Buddy
的数组。 Sometimes though, when I want to inherit Alfred
, I also want to override class Buddy
with some functionality specific to the new derived form, AlfredJunior
. 有时候,当我想继承
Alfred
,我也希望用一些特定于新派生形式AlfredJunior
功能来覆盖类Buddy
。
So, in the definition of class Alfred
: 所以,在
Alfred
类的定义中:
protected Array<Buddy> importantArray;
And what I want in AlfredJunior
is this: 而我在
AlfredJunior
想要的是:
private class BuddyJunior : Buddy
{
public int newField;
// Constructors omitted
}
protected Array<BuddyJunior> importantArray;
I'd like for the methods defined in Alfred
to access and use the elements of importantArray
just as if they were of type Buddy
, instead of BuddyJunior
. 我希望
Alfred
定义的方法能够访问和使用importantArray
的元素,就好像它们是Buddy
类型,而不是BuddyJunior
。 But I need just a touch of extra functionality (one extra field) in BuddyJunior
in the inherited form AlfredJunior
. 但我需要在
BuddyJunior
中继承一些额外的功能(一个额外的字段),继承的形式是AlfredJunior
。 What is the correct way to go about this? 这是怎样的正确方法?
This is what you need: 这就是你需要的:
public abstract class Alfred<B> where B : Buddy
{
protected B[] importantArray;
}
public class Buddy { }
public class BuddyJunior : Buddy
{
public int newField;
}
public class Alfred : Alfred<Buddy> { }
public class AlfredJunior : Alfred<BuddyJunior> { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.