2012-10-05 59 views
2

有人可以解释下面的类声明。我已经被赋予一个任务来理解代码片段并解释其中的部分内容。我无法理解这个类的声明。看看你们有没有人可以帮忙。c#泛型类定义解释

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); 
    } 
} 

回答

1

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

代码的好处是:

  • 新():您可以访问构造函数和实例化您的类中的新型T。
  • IContinentFactory:您可以访问使用T.
1

首先的对象时,在该接口中声明的所有元素,AnimalWorld是应该实现IAnimalWorld接口(T)的一个泛型类。

“where”关键字是T类型的约束,说T必须实现IContintentFactory并且有一个不需要参数的公共构造函数。

0

该类代表动物世界。这个世界在大陆上分开(用T通用参数表示)。

当你创建一个新的AnimalWorld,类需要指定在哪个洲,你是通过提供一个类有一个空的构造器(该T泛型参数)(该new()约束)的实现了接口IContinentFactory(该IContinentFactory )。

让我们举个例子:如果Europe被定义如下AnimalWorld<Europe> = new AnimalWorld<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