【问题标题】:In C# how can I create an IEnumerable<T> class with different types of objects>在 C# 中,如何创建具有不同类型对象的 IEnumerable<T> 类>
【发布时间】:2013-07-22 19:09:18
【问题描述】:

在 C# 中,如何创建具有不同类型对象的 IEnumerable&lt;T&gt;class

例如:

Public class Animals
{

Public class dog{}

Public class cat{}

Public class sheep{}

}

我想做一些类似的事情:

Foreach(var animal in Animals)
{
Print animal.nameType
}

【问题讨论】:

  • 实现IEnumerable,继承自ArrayListCollectionBaseList&lt;t&gt;
  • 您可能会考虑将Animal 设为abstract 基类,因为如果没有是某种更具体的动物,则没有任何东西是Animal

标签: c# .net object collections ienumerable


【解决方案1】:

如果你想要一个命名集合,另一种方法(而不是使用 List&lt;T&gt;):

// animal classes
public class Animal
{
    public String Name { get; set; }
    public Animal() : this("Unknown") {}
    public Animal(String name) { this.Name = name; }
}
public class Dog : Animal
{
    public Dog() { this.Name = "Dog"; }
}
public class Cat : Animal
{
    public Cat() { this.Name = "Cat"; }
}

// animal collection
public class Animals : Collection<Animal>
{

}

实施:

void Main()
{
    // establish a list of animals and populate it
    Animals animals = new Animals();
    animals.Add(new Animal());
    animals.Add(new Dog());
    animals.Add(new Cat());
    animals.Add(new Animal("Cheetah"));

    // iterate over these animals
    foreach (var animal in animals)
    {
        Console.WriteLine(animal.Name);
    }
}

在这里,您扩展了实现IEnumerable&lt;T&gt;Collection&lt;T&gt; 的基础(所以foreach 和其他迭代方法都可以使用它)。

【讨论】:

    【解决方案2】:

    创建一个 Animal 基类。让每个特定的动物都继承自 Animal。在 Animal 中创建一个名为 NameType 的抽象方法,每个子类都将覆盖该方法。创建一个List&lt;Animal&gt; 并对其进行迭代。

    【讨论】:

      【解决方案3】:
      public class Animal {
      
      }
      
      public class Dog : Animal {
      
      }
      
      public class Cat : Animal {
      
      }
      
      
      List<Animal> animals = new List<Animal>();
      
      animals.Add(new Dog());
      animals.Add(new Cat());
      

      然后您可以通过以下方式遍历集合:

      foreach (var animal in animals) {
          Console.WriteLine(animal.GetType());
      }
      

      【讨论】:

      • @newStackExchangeInstance - 是的。
      猜你喜欢
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      相关资源
      最近更新 更多