任意对象选择 [英] Arbitrary object selection

查看:69
本文介绍了任意对象选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类动物".我有2个从Animal继承的类,"Dog"和"Cat". Dog和Cat的方法和属性名称相同,但是详细信息不同.在程序运行期间,我想使用OptionBox(或其他)或Dog或Cat进行选择.在我看来,要做到这一点,就必须能够使用一种常见的动物,例如小动物".能够看起来像狗或猫,是为了实例化合适的动物.我正在使用Visual Studio Pro 2005在C#中对此进行编程.如果有人有解决方案,请发邮件或将其发送到[删除垃圾邮件磁铁].
谢谢,Bob

I have a base class "Animal". I have 2 classes inherited from Animal, "Dog" and "Cat". Dog and Cat have identical methods and properties names, but their details are different. During the running of the program I want to select using an OptionBox (or something else) either Dog or Cat. It seems to me that In order to do this, one would have to be able to use a common animal such as "Critter"; to be able to appear to be Dog or Cat be for instantiating the right animal. I''m programming this in C# using Visual Studio Pro 2005. If anyone has an approach to the solution, please post or email to [spam magnet removed].
Thanks, Bob

推荐答案

OK,所以您希望您的Animal成为成员变量,这样当您按下Talk按钮时它就在范围内.

OK, so you want your Animal to be a member variable, so that it''s in scope when you push the Talk button.

public partial class Form1 : Form
{
    private Animal animal;

    private void btnDog_Click(object sender, EventArgs e)
    {
        animal = new Dog();
    }

    private void btnCat_Click(object sender, EventArgs e)
    {
        animal = new Cat();
    }

    private void btnTalk_Click(object sender, EventArgs e)
    {
        if (animal != null)
        animal.Talk();
    }
}



添加了前置标记



Added pre tags


我不确定我是否遵循此规则.您的动物"类是动物".您将拥有一组动物,每个动物都可以是狗"或猫"的实例.

就像别人说的那样,我们不会做作业,除非问题很明确,并且附带代码来显示您自己尝试过,因为这样做是100%的重点.在这种情况下,我认为您已经考虑过了,这就是为什么我试图提供帮助,但是我承认我并没有完全理解问题所在.
I''m not sure I follow this. Your ''Critter'' class, is ''Animal''. You would have a collection of animals, which could each be instances of ''dog'' or ''cat''.

As someone else said, we don''t do homework, not unless the question is very specific and comes with code to show you''ve tried to do it yourself, given that trying to do it is 100% the point. In this case, I think you''ve thought about it, which is why I''ve tried to help, but I admit I don''t follow what the issue is, exactly.


public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnDog_Click(object sender, EventArgs e)
    {
        Animal dog = new Dog();
        dog.Talk();  // I don't want the dog to talk here
    }

    private void btnCat_Click(object sender, EventArgs e)
    {
        Animal cat = new Cat();
        cat.Talk();  // Nor do I want the cat to talk here
    }

    private void btnTalk_Click(object sender, EventArgs e)
    {
        // I want the dog or cat to talk here depending on whether i pushed the "Dog" or "Cat" button
    }
}


这篇关于任意对象选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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