简体   繁体   中英

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. In the abstract base class, which we'll call Alfred , I have an array of type 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 .

So, in the definition of class Alfred :

protected Array<Buddy> importantArray;

And what I want in AlfredJunior is this:

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 . But I need just a touch of extra functionality (one extra field) in BuddyJunior in the inherited form 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> { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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