2012-10-05 61 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