簡體   English   中英

如何允許 class 接受另一個 class 的所有派生類?

[英]How to allow a class to accept all derived classes of another class?

I am making an enemy script which uses a state machine based on classes, I have made a State class which all the different states are derived from and each of these classes require an EnemyController class for its variables and methods. 我還制作了 3 個不同的敵人類,它們從 EnemyController class 派生,但這些無法輸入到狀態中。 我想找到一種方法,以便我可以將這三個敵人腳本輸入到狀態中,但它們似乎只采用父級 EnemyController 腳本。

public State(EnemyController enemy)
{
    this.enemy = enemy;
}

每個狀態都需要一個 EnemyController 參數,但我希望它能夠使用 EnemyControllerA、EnemyControllerB 或 EnemyControllerC,因為每個敵人 controller 對於每個敵人都略有不同。

我不確定您是否是您所指的,因為問題不是很清楚。 如果不是,我建議您分享更完整的嘗試,以縮小您的問題范圍。

我感覺你可能會追求的是,接口實現的類型可以是孩子的持有人類型。 這適用於從接口實現的類,或從其他類繼承的類。 在控制台應用程序代碼示例下面找到接口實現和 class inheritance 我的意思。

界面:

namespace ConsoleApp
{
    public interface IMethodsToImplement
    {
        void method1();
        void method2();
    }

    public class InterfaceImplementer : IMethodsToImplement
    {
        public InterfaceImplementer() {

        }

        public void method1()
        {
            // whatever
        }

        public void method2()
        {
            // whatever
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<IMethodsToImplement> holderList = new List<IMethodsToImplement>() {
                new InterfaceImplementer(), new InterfaceImplementer() 
            };

            Console.WriteLine($"InterfaceImplementer count: {holderList.Count}");
            Console.ReadLine();
        }
    }
}

從另一個 class 繼承:

using System.Collections.Generic;

namespace ConsoleApp
{
    public class A { 
    
    }

    public class B : A
    {
        public B() {

        }

        public void method1()
        {
            // whatever
        }

        public void method2()
        {
            // whatever
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<A> holderList = new List<A>() {
                new B(), new B() 
            };

            Console.WriteLine($"InterfaceImplementer count: {holderList.Count}");
            Console.ReadLine();
        }
    }
}

在這兩種情況下,獲得的 output 是InterfaceImplementer count: 2請注意基本類型或實現的接口如何充當 inheritance 或實現鏈中的任何子項的標識類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM