在 C# 中选择一个不知道子类名称的子类

Choosing a Subclass without knowing the name of it in C#

编辑 1:If 谁有更好的标题,请随时告诉我或自己编辑。
编辑 2:感谢你们的贡献,给出的答案几乎是我需要的一些调整,我很感谢这里的小东西。今天真的学到很多!

这里有些小东西,我现在一直在努力。
我想创建一个幻灯片并想要图像 objects 本身的逻辑。

该程序应该能够设置所需的过渡或只是一个随机过渡
我想用一般的东西创建一个 Transition Superclass 并 spezialize
它在 subclasses 中。所以我有 Transitions.cs(目前里面没有代码)
并且没有派生 class。我希望它妨碍添加单个 .cs 文件
扩展 Transitions.cs 并且不更改任何其他代码以实现新的转换。

我目前的代码看起来像这样,但我想我的
描述比代码更有帮助

public class SlideImages : MonoBehaviour {

    Image image;
    Image nextImage;
    int tracker;

    private void Transition(int ID)
    {
        /*Something to choose a transition based on the ID
        *Transitions.cs is the superclass of all different transitions
        *f.e. Ken-Burns Effect, or scattered Transition which all extend from it
        */
    }

    ~SlideImages()
    {
        //TODO: Pop and Push
    }
}

我想到了一些类似静态的东西来解决这个问题
看起来像这样,但我想它不起作用

public class Transitions : MonoBehaviour {

    public static int TransitionID;
    protected static int SubclassCount;

    protected static void SetID()
    {
        TransitionID = Transitions.SubclassCount;
        Transitions.SubclassCount++;
    }
}

我确实研究了状态设计模式,但我不想实现它,因为我只需要选择一次状态并且寿命很短。 Image Objects 本身只有几秒钟的生命周期。我不想做通常的 if-nesting 或只是将所有代码放在 SlideImages.cs 中。有什么好的指导或深入继承的东西吗?

感谢所有意见。

对于您想要做的事情,有两种直接的解决方案。您的基本问题是您希望能够动态地向您的程序添加功能,但您不想知道为了使用它而添加的内容。最 hack-ish 的方法是使用 Actions 而不是 subclassing。当你想添加另一个转换时,你只需像这样更新一个动作列表:

public static class Transitions
{
    private static Action[] TransitionStrategies = new Action[]
    {
        () => { /* One way of performing a transition */ },
        () => { /* Another way of performing a transition */ },
        () => { /* Keep adding methods and calling them here for each transition type */ }
    }

    public static void PerformTransition(int? transitionIndex = null)
    {
        int effectiveIndex;

        // if the transition index is null, use a random one
        if (transitionIndex == null)
        {
            effectiveIndex = new Random().Next(0, TransitionStrategies.Length);
        }
        else
        {
            effectiveIndex = transitionIndex.Value;
        }

        // perform the transition
        TransitionStrategies[effectiveIndex]();

    }
}

上述方法很简单,但所有逻辑(或至少对逻辑的引用取决于您在何处实现转换的实际工作)都在一个地方。它也有可能变得相当混乱,具体取决于您添加了多少转换以及有多少开发人员正在接触此代码库。它还要求有权访问完整代码库的人员添加所有功能,并且每次添加新转换时都需要重新编译。

从长远来看,一种更复杂但更易于维护和灵活的方法是使用模块(或我们的目的插件)。该方法中的每个转换都由共享模块或特定模块提供,并且是基础 AbstractTransition class 的子 class 或 ITransition 接口的实现,具体取决于关于你想如何去做。使用 post-build 任务将所有模块 dll 放在主程序可访问的单个目录中(任何其他获得许可的人也可以将转换模块 dll 放在那里)。当您的程序启动时,它会动态加载该目录中的所有 dll(只要正确的 dll 在该目录中,添加新转换时不需要重新编译)并提取所有实现该接口的 classes。这些接口实现中的每一个都被实例化并放入数据结构中,之后您可以使用与上述 PerformTransition 方法类似的策略来执行随机一个或一个基于 ID 而不是索引。如果您愿意,我可以使用该结构的示例来编辑此问题。

编辑:你还没有要求它,但这里有一个 plugins/modules 的例子。

首先,创建一个项目来加载和运行 转换。此示例将使用名为 ModuleDemo 的项目。给它一个像这样的主要方法:

static void Main(string[] args)
{
    // create a list to hold the transitions we load
    List<AbstractTransition> transitions = new List<AbstractTransition>();

    // load each module we find in the modules directory
    foreach (string dllFilepath in Directory.EnumerateFiles("Modules", "*.dll"))
        // this should really read from the app config to get the module directory                
    {
        Assembly dllAssembly = Assembly.LoadFrom(dllFilepath);

        transitions.AddRange(dllAssembly.GetTypes()
            .Where(type => typeof(AbstractTransition).IsAssignableFrom(type))
            .Select(type => (AbstractTransition) Activator.CreateInstance(type)));
    }

    // show what's been loaded
    foreach (AbstractTransition transition in transitions)
    {
        Console.WriteLine("Loaded transition with id {0}", transition.TransitionId);

        // execute just to show how it's done
        transition.PerformTransition();
    }

    Console.Read(); // pause
}

您会注意到该方法引用了 AbstractTransition class。现在让我们为此创建一个单独的 TransitionModule 项目。这是模块将引用的项目:

namespace TransitionModule
{
    public abstract class AbstractTransition
    {        
        public readonly int TransitionId;
        public abstract void PerformTransition();

        protected AbstractTransition(int transitionId)
        {
            TransitionId = transitionId;
        }

        // you can add functionality here as you see fit
    }
}

现在我们有了要实现的插件的抽象转换 class 和功能正常的插件加载器,我们可以继续创建一些转换插件。

我在我的解决方案中为此创建了一个 Modules 文件夹,但这并不重要。

FlipTransition 项目中的第一个模块:

using System;
using TransitionModule;

namespace FlipTransition
{
    public class FlipTransition : AbstractTransition
    {
        public FlipTransition() : base(2)
        {
        }

        public override void PerformTransition()
        {
            Console.WriteLine("Performing flip transition");
        }
    }
}

SlideTransition 项目中的第二个模块:

using System;
using TransitionModule;

namespace SlideTransition
{
    public class SlideTransition : AbstractTransition
    {
        public SlideTransition() : base(1)
        {
        }

        public override void PerformTransition()
        {
            Console.WriteLine("Performing slide transition");
        }
    }
}

请注意,每个项目都需要引用 TransitionModule 项目,但主项目不需要了解任何其他项目。

现在我们有 2 个转换插件和一个插件加载器。由于插件加载器将从 Modules 目录加载模块,因此转到主项目的 /bin/Debug 目录并创建一个 Modules 目录。将过渡插件项目的 /bin/Debug 目录中的所有 dll 也复制到该目录中。所有这些都可以通过 post-稍后构建任务自动完成。

继续 运行 程序。你应该得到这样的输出:

Loaded transition with id 2
Performing flip transition
Loaded transition with id 1
Performing slide transition

您可以做很多事情来使它更优雅,但这至少是一个简单的示例,说明您如何使用基于插件的架构来提供您需要的东西。

您可以尝试使用抽象 classes,创建一个基础抽象 class 用于图像转换;

public abstract class ImageTransition
{
    protected int imageId { get; set; }
    public Dictionary<int, Image> ImageDictionary { get; set; }

    protected abstract void TransitionToNextImageId();

    public Image GetNextImage()
    {
        TransitionToNextImageId();
        return ImageDictionary[imageId];
    }
}

然后创建继承自该基础的新过渡类型 class 并拥有自己的 TransitionToNextImageId 方法实现;

public class InTurnImageTransition : ImageTransition
{
    protected override void TransitionToNextImageId()
    {
        if(this.imageId < ImageDictionary.Count)
            this.imageId ++;
    }
}

public class RandomImageTransition : ImageTransition
{
    protected override void TransitionToNextImageId()
    {
        imageId = new Random().Next(0, ImageDictionary.Count);
    }
}

这允许您根据需要构建一些自定义转换。

-编辑- 在调用 GetNextImage 方法之前,您当然会填写字典 ImageDictionary。