2013-10-29 42 views
-4

這是我正在使用的代碼,它在實例化時有構建錯誤。我不知道爲什麼它沒有看到,我的SpecialHandler的類型是BaseHandler的以T設置爲SpecialEntity爲什麼泛型沒有看到我的繼承?

static class HandlerFactory 
{ 
    public static BaseHandler<BaseEntity> Create(string typeString) 
    { 
     throw new NotImplementedException(); 
    } 

    public static BaseHandler<T> Create<T>(string typeString) where T : BaseEntity { 
     if (typeString == "Special") 
      **return new SpecialHandler();** //THERE'S BUILD ERROR HERE EVEN THOUGH Special Handler is inherits from type BaseHandler<T> 
     else 
      return null; 
    } 
} 

public class BaseHandler<T> where T : BaseEntity 
{ 
    public T GetEntity() 
    { 
     throw new NotImplementedException(); 
    } 
} 

public class SpecialHandler : BaseHandler<SpecialEntity> {} 

public class BaseEntity{} 

public class SpecialEntity : BaseEntity{} 
+7

你能解釋一下問題是什麼以及問題的含義是什麼? – SWeko

+0

請描述你正在觀察的行爲。 – Gusdor

+2

偉大的純代碼。如果人們傾向於說,請張貼代碼,但這並不意味着不需要描述。 – Tafari

回答

2

(用我的心理調試技能來推斷問題)除另有指明

(和它的作品只無論如何),遺傳參數是不變的,即確切的。
定義爲List<Mammal>的集合與定義爲List<Animal>的集合或定義爲List<Cat>的集合沒有任何關係。

Create法說,它返回一個BaseHandler<BaseEntity>,不是BaseHandler<SpecialEntity>,你的SpecialHandler是-A BaseHandler<SpecialEntity>,但它不是一個BaseHandler<BaseEntity>

+0

壯觀的心理調試技巧:) –

+0

謝謝SWeko。你的解釋很容易理解......並且你也有很好的心理技能:) –