2014-05-07 23 views
1

我有這樣的網絡API控制器動作:KnownType屬性不能使用類型參數

public Plant<TissueProductionLine> GetPlant(string plant, string range) 
{ 
    return _repo.GetPlant(plant, range); 
} 

射擊這件事我得到這個:

Type 'IGMProdLineDashboard.Models.TissueProductionLineGroup' with data contract name 'IGMProdLineDashboard.Models' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

行,沒問題,我就裝飾我的Plant對象具有[KnownType]屬性並指定非原始屬性:

[KnownType(typeof(ProductionLineGroups<T>))] 
public class Plant<T>: IPlant<T> where T : IProductionLine 
{ 
    public Plant() 
    { 
     ProductionLineGroups = new ProductionLineGroups<T>(); 
    } 
    public ProductionLineGroups<T> ProductionLineGroups { get; set; } 

現在我得到一個編譯時錯誤:

'IGMProdLineDashboard.Models.ProductionLineGroups': an attribute argument cannot use type parameters

重讀的第一個消息,它想知道派生類型:TissueProductionLineGroup

如果我裝飾我的Plant這個目標,一切工作:

[KnownType(typeof(TissueProductionLineGroup))] 

顯然這裏的含義是我現在Plant需要了解各種不同類型的生產線,這意味着我需要更新時添加新組Plant

有沒有辦法解決這個問題?

回答

0

不幸的是,錯誤信息並沒有誤導你。屬性不能使用泛型類型參數。據我所知,這個問題沒有辦法解決。

Jon Skeet確實發佈了一個關於此問題的答案,並表示C#團隊選擇添加這種限制以保持編譯器代碼更簡單,儘管沒有任何理由說明CLI不能代表通用屬性。

請參閱:https://stackoverflow.com/a/294259/2394286

+0

是的,我看到它也有點熱。不幸的是,這種情況是耦合我的代碼,我曾努力保持解耦... –

+1

Skeet先生的名字中沒有'h'。 –

相關問題