2

有人可以解释以下类声明。我被分配去理解一段代码并解释它的各个部分。我无法理解此类声明。看看有没有人可以帮忙。

class AnimalWorld<T> : IAnimalWorld where T : IContinentFactory, new()
{
    private IHerbivore _herbivore;
    private ICarnivore _carnivore;
    private T _factory;

    /// <summary>
    /// Contructor of Animalworld
    /// </summary>
    public AnimalWorld()
    {
        // Create new continent factory
        _factory = new T();

        // Factory creates carnivores and herbivores
        _carnivore = _factory.CreateCarnivore();
        _herbivore = _factory.CreateHerbivore();
    }

    /// <summary>
    /// Runs the foodchain, that is, carnivores are eating herbivores.
    /// </summary>
    public void RunFoodChain()
    {
        _carnivore.Eat(_herbivore);
    }
}
4

4 回答 4

3

T : IContinentFactory, new()

  1. T 必须从 IContinentFactory 继承
  2. T 必须有无参数构造函数。

更多信息:http new(): //msdn.microsoft.com/en-us/library/sd2w2ew5.aspx

于 2012-10-05T08:21:03.070 回答
1

首先,AnimalWorld 是一个泛型类(属于 T),它应该实现 IAnimalWorld 接口。

“where”关键字之后是对 T 类型的约束,表示 T 必须实现 IContintentFactory 并具有不需要参数的公共构造函数。

于 2012-10-05T08:19:11.167 回答
1

它说 T 必须是 IContinentFactory 类型并且必须有一个空的构造函数。

该代码的好处是:

  • new():你可以访问构造函数并在你的类中实例化一个新的 T。
  • IContinentFactory:使用 T 对象时,您可以访问在该接口中声明的所有元素。
于 2012-10-05T08:17:34.277 回答
0

这个类代表一个动物世界。这个世界被分成几大洲(由T通用参数表示)。

当您创建一个 newAnimalWorld时,该类要求您通过提供一个T具有空构造函数(new()约束)的类(泛型参数)并实现接口IContinentFactory(the IContinentFactory)来指定您所在的大陆。

让我们举个例子:AnimalWorld<Europe> = new AnimalWorld<Europe>()如果Europe定义如下:

class Europe : IContinentFactory
{
  // Don't forget the new() constructor
  Europe()
  {
     //...//
  }

  // Here IContinentFactory implementation 
  public IHerbivore CreateHerbivore()
  {
    //...//
  }

  // Here IContinentFactory implementation 
  public ICarnivore CreateCarnivore()
  {
    //...//
  }
}

除此之外,AnimalWorld<T>从接口派生IAnimalWorld

于 2012-10-05T09:04:39.773 回答