简体   繁体   English

如何在抽象类中声明任何类型的数组(从给定类型派生)?

[英]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.

相关问题 如何遍历包含从该抽象 class 派生的非抽象类型的抽象类型列表? - How could I iterate through list of abstract type, containing non-abstract types derived from that abstract class? 检查类型是否派生自抽象泛型类 - Check if type is derived from abstract generic class 如何使用Singleton将派生类型传递给抽象类 - How to pass derived type to abstract class with singleton 将方法上的泛型类型约束为从抽象泛型基类的任何变体形式派生的任何类 - Constrain generic type on a method to be any class that is derived from any variant form of an abstract generic base class 我如何引用来自基础 class 的派生类型? - how do i refer to the derived type from the base class? 有什么方法可以访问抽象类的派生类类型 - Is any way to get access to derived class type for abstract one 如何将泛型类型的抽象类约束到派生类的接口? - How to constrain generic type of abstract class to interface of derived class? C# 如何从基类中的派生类获取特定类型的所有字段? - C# How do I get all the fields of a specific type from a derived class within the base class? 在抽象类中声明子类类型的变量 - Declare Variable of Child Class Type in Abstract Class 如何限制添加到派生类的项目类型? - How do I restrict the type of items added to a derived class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM