[英]Type of generics method return value
在我看來,我應該能夠做到這一點? 但我不能。
public Dictionary<Type, List<ParserRuleContext>> Contexts { get; private set; }
public IEnumerable<T> GetAllContextsOfType<T>() where T:ParserRuleContext
{
return (List<T>)Contexts[typeof(T)];
}
這會產生錯誤:
Cannot convert type 'System.Collections.Generic.List<ParserRuleContext>'
to 'System.Collections.Generic.List<T>'
鑒於List被子句限制為List <ParserRuleContext>,我不明白這一點?
我認為應該是這樣一個事實,即列表中的實例與字典中的列表具有不同的尖端,如果你使用linq進行轉換就是要解決
return Contexts[typeof(T)].Cast<T>();
要么
return Contexts[typeof(T)].ToList<T>();
僅僅因為您知道,對於特定Type
,您只需要在此處存儲的List<ParserRuleContext>
存儲該特定類型的對象1 :
public Dictionary<Type, List<ParserRuleContext>> Contexts
類型系統還沒有足夠的信息來了解這一事實。 就它而言,每個列表都可以包含所有類型的對象,所有對象都來自ParserRuleContext
。 這樣的列表顯然不能直接轉換為任何更具體的列表類型。
並且泛型類型(通常)不鏡像其類型參數所做的任何繼承結構。 因此,您可能在此字典中存儲了List<TypeDerivedFromParserRuleContext>
,因為List<TypeDerivedFromParserRuleContext>
不會從List<ParserRuleContext>
繼承。
1至少,我認為這是你認為其余代碼“有意義”的假設
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.