如何存储和使用从通用基本类型派生的不同类型的数组? [英] How can I store and use an array of different types derived from a common base type?

查看:81
本文介绍了如何存储和使用从通用基本类型派生的不同类型的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题可能需要一些解释,所以这是我想要做的:

The title may need a bit of explanation, so here's what i'm trying to do:

  • UI元素的通用基本类型,例如BasePanel
  • 可以定义更多专门元素,这些元素派生自BasePanel.例如,按钮和文本框.
  • 将存储元素列表(BasePanel类型,以便可以存储专门的元素)
  • 此列表将遍历每一帧并绘制(此刻忽略优化)

示例用法:

class UIButton : BasePanel
{
    public override void Draw(blah)
    {
        // Specialised drawing code
    }
}

foreach (BasePanel Element in StoredElements)
{
    Element.Draw(blah);
}

问题是它不会运行专门的代码.它只会运行BasePanel代码. 我该如何改善它,使其改为运行专用代码?我可以将元素的类型存储在BasePanel上,然后在运行时强制转换为它吗?

The problem with this is that it won't run the specialised code; it will just run the BasePanel code. How can I improve this so that it will run the specialised code instead? Could I store the type of the element on the BasePanel, and then cast to it at runtime?

我尝试将BasePanel存储在存储原始类型的Container类中,但无法访问该方法-例如:

I've tried storing the BasePanel in a Container class which stores the original type, but I can't access the method - for example:

foreach(ElementContainer Container in StoredElements)
{
    Type t = Container.OriginalType;
    object el = Container.Element;

    Convert.ChangeType(el, t); //Can't use the returned object!

    t Element = (t)Convert.ChangeType(el, t); //This would be perfect, but it doesn't work.
}

感谢您的帮助.这使我的大脑爆炸了.

Thanks for any help. This has made my brain explode.

推荐答案

使用以下代码对我来说100%有效:

It works 100% for me with the following code:

class BasePanel
{
    public virtual void Draw(string blah)
    {
        Console.WriteLine("Base: " + blah);
    }
}

class UIButton : BasePanel
{
    public override void Draw(string blah)
    {
        Console.WriteLine("UIButton: " + blah);
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<BasePanel> list = new List<BasePanel>();

        list.Add(new BasePanel());
        list.Add(new UIButton());
        list.Add(new BasePanel());
        list.Add(new UIButton());
        list.Add(new UIButton());

        foreach (var b in list)
        {
            b.Draw("just a string");
        }
    }
}

您的问题出在您的图形代码/逻辑上.

What is wrong with yours comes from your drawing code/logic.

这篇关于如何存储和使用从通用基本类型派生的不同类型的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆