泛型方法的类型返回值

And*_*age 3 c# generics

在我看来,我应该能够做到这一点?但我不能.

public Dictionary<Type, List<ParserRuleContext>> Contexts { get; private set; }

public IEnumerable<T> GetAllContextsOfType<T>() where T:ParserRuleContext
{
    return (List<T>)Contexts[typeof(T)];
}
Run Code Online (Sandbox Code Playgroud)

这会产生错误:

Cannot convert type 'System.Collections.Generic.List<ParserRuleContext>' 
to 'System.Collections.Generic.List<T>'
Run Code Online (Sandbox Code Playgroud)

鉴于List被子句限制为List <ParserRuleContext>,我不明白这个?

小智 6

我认为应该是这样一个事实,即列表中的实例与字典中的列表具有不同的尖端,如果你使用linq进行转换就是要解决

return Contexts[typeof(T)].Cast<T>();
Run Code Online (Sandbox Code Playgroud)

要么

return Contexts[typeof(T)].ToList<T>();
Run Code Online (Sandbox Code Playgroud)