【问题标题】:How to allow a class to accept all derived classes of another class?如何让一个类接受另一个类的所有派生类?
【发布时间】:2021-06-08 16:28:12
【问题描述】:

我正在制作一个使用基于类的状态机的敌人脚本,我制作了一个 State 类,所有不同的状态都来自该类,并且每个类都需要一个 EnemyController 类作为其变量和方法。我还制作了 3 个不同的敌人类,它们派生自 EnemyController 类,但这些无法输入到状态中。我想找到一种方法,以便我可以将这三个敌人脚本输入到状态中,但它们似乎只采用父级 EnemyController 脚本。

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

每个状态都需要一个 EnemyController 的参数,但我希望它能够使用 EnemyControllerA、EnemyControllerB 或 EnemyControllerC,因为每个敌人的控制器对每个敌人都略有不同。

【问题讨论】:

  • 给我们看一些代码:)
  • “这些不能输入到状态中” - 为什么不呢?你得到什么错误?您应该能够传入EnemyController 的任何派生类。

标签: c# class unity3d inheritance state


【解决方案1】:

我不确定您是否是您所指的,因为问题不是很清楚。 如果不是,我建议您分享更完整的尝试,以缩小您的问题范围。

我感觉您可能会追求的是,​​接口实现的类型可以是子级的持有者类型。这适用于从接口实现的类,或从其他类继承的类。找到下面的控制台应用程序代码示例,了解我的意思的接口实现和类继承。

界面:

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();
        }
    }
}

从另一个类继承:

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();
        }
    }
}

在这两种情况下,得到的输出都是InterfaceImplementer count: 2 请注意基类型或实现的接口如何充当继承或实现链中的任何子项的标识类型。

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2011-11-14
    • 2020-07-28
    相关资源
    最近更新 更多