-1

我有我坚持的 AnimalModel 程序。该程序包含一个抽象类动物,其子类为哺乳动物、昆虫、鸟类、爬行动物和海洋。在每个亚类中还有另外两个动物亚类。

例如,哺乳动物有 Wolf 和 Dog 类。

我的问题是我创建了一种将动物项目添加到数组的方法。

我正在尝试将包含例如狼或狗的列表视图中的对象投射到哺乳动物对象但没有成功..

我已经尝试了两种方法,它们都不起作用..

private void AddAnimalItem() 
{
    string m_age = txtAge.Text;
    string m_Name = txtName.Text;

    CategoryType m_CategoryType = (CategoryType)(lstCtgr.SelectedIndex);
    Animals animal = null;

    switch(m_CategoryType)
    {
        case CategoryType.Mammal:

            // first attempt
            Mammal mammalspecies  = (Mammal)Enum.Parse(typeof(Mammal),
                                        lstAnml.SelectedItem.ToString());

            // second attempt
            Mammal mammalspecies = lstAnimal.SelectedItems.Cast<Mammal>();

            // Static method for creating an Mammal to an animal
            animal = Mammal.MammalFactory(mammalspecies);
            break;
    }

    /* ... */
 }
4

2 回答 2

0

You really should provide more information for your question. Since you haven't provided enough information, I need to make a few assumptions:-

  • Mammal is a class, not an enum. (Because enums cannot have subclasses or sub-enums.)
  • CategoryType is an enum, not a class, but one of its values is also called Mammal (ie. CategoryType.Mammal).
  • lstAnml is a ListBox, and its values are strings that are the fully-qualified class names of the Mammal subclasses (eg. "MyNamespace.Wolf", "MyNamespace.Dog").
  • Mammal, Wolf, and Dog classes all have parameterless constructors.

If my above assumptions are wrong, please update your question with the missing information.

If my above assumptions are correct, then replace your first/second attempt with the following:-

Type mammaltype = Type.GetType(lstAnml.SelectedItem.ToString());
Mammal mammalspecies = (Mammal) Activator.CreateInstance(mammaltype);

However, your last statement's logic seems to be wrong. Mammal.MammalFactory() should be taking in an enum as a parameter, not a class instance. But if Mammal really is an enum, then it cannot have subclasses...

So assuming Mammal really is a class, not an enum, then your last statement should simply be:

animal = mammalspecies;
于 2012-07-30T23:41:31.050 回答
0

我会为这段代码提出很多建议,其中最少的是:

  1. 使用 lstCtgr 不要将序数转换为另一种类型(我假设是枚举),我将清除一个列表项类,其中包含项目的文本表示(ToString),并且能够独立于顺序获取实际 CategoryType列表。
  2. 我会用 lstAnimal 做类似的事情。如果您需要获取有关超出其序数的选择的信息,我将创建您可以添加到 lstAnimal 的类,该类为您提供该信息。很像 lstCtr,在实现 ToString 并提供对 Mammal 对象的访问的类型。

但是,非常不清楚您需要做什么,甚至您要使用您发布的代码做什么。既要选择动物类别 (lstCtgr) 又要选择实际动物 (lstAnml) 是没有意义。动物在 lstAnml 中的位置似乎完全独立于 lstCtr。

于 2012-07-30T23:08:00.017 回答