繁体   English   中英

C#类工厂新手

[英]c# class factory newbie

这可能是我要找的标题错误,但我认为它归结为一个类工厂。

我有三节课:

   class Horse : Animal
   class Cow :   Animal

我要创建的是Animal中的一种方法,该方法经过伪编码后将像这样工作:

   List<Horse or Cow> (Animal horseOrCow)
   {
      if (horseOrCow is of type Horse)
         return a list of 10 Horse objects; 
      else
         return a list of 10 Cow objects;
   }

当然可以简化,但是一旦我掌握了如何做到这一点,我应该就能弄清楚其余的事情。

(编辑:错字固定)。

您可以使用类型的通用方法

List<T> YourMethod<T>(T horseOrCow) where  T : Mamal
{
   // your code
}

您可以使用is -operatorEnumerable.OfType + Enumerable.Take

public List<Animal> getMammals(Mammal horseOrCow)
{
    if (horseOrCow is Horse)
        return allAnimals.OfType<Horse>().Take(10).Cast<Animal>().ToList();
    else if (horseOrCow is Cow)
        return allAnimals.OfType<Cow>().Take(10).Cast<Animal>().ToList();
    else
        throw new ArgumentException("Invalid Mammal", "horseOrCow");
}

假设某处有一个List<Animal> allAnimals

编辑Mammal也必须是Animal并且由于HorseCowMammals因此它们应该从中继承。

class Horse : Mammal{ }
class Cow : Mammal { }
class Animal { }
class Mammal : Animal { }

这应该为您工作:

abstract class Animal
abstract class Mammal : Animal  
class Horse : Mammal 
class Cow :   Mammal 

List<T> (T mammal) where  T : Mammal  //mammal is cow or horse
{
   if (horseOrCow is Horse)
      return new List<Horse>(); //add the horses to your list 
   else
      return new List<Cow>(); //add the cows to your list
}
public class Animal
{
    public List<Mammal> GetMammalList(Mammal mammal)
    {
        List<Mammal> list = new List<Mammal>();
        if (mammal.GetType() == typeof(Horse))
            for (int x = 0; x < 10; x++)
                list.Add(new Horse());
        else if (mammal.GetType() == typeof(Cow))
            for (int x = 0; x < 10; x++)
                list.Add(new Cow());
        else
            throw new ArgumentOutOfRangeException();

        return list;
    }
}

public class Mammal : Animal { }

public class Horse : Mammal { }

public class Cow : Mammal { }

我不建议使用is类型检查。 而是使用dynamic来确定对象的运行时类型。

public void List<T> GetMammals<T>(T mammal) where  T : Mammal
{
   GetMammalsSpecialization(mammal as dynamic);
}

private void List<Horse> GetMammalsSpecialization(Horse horse)
{
    // Specialized code to return list of horses
}

private void List<Cow> GetMammalsSpecialization(Cow cow)
{
    // Specialized code to return list of cows
}

这是双重调度问题的更好解决方案。

public class Animal
{ 
   public enum AnimalType
   {
     CowType,
     HorseType
   }


   ....
   public Animal Create(AnimalType type)
   {
     Animal result = null;
      switch (type)
      {
       case HorseType: result = new Horse();
       case CowType : ....   
      }
     return result;
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM