Generics method return type

It seems to me that I should do this? But I can not.

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

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

This results in an error:

Cannot convert type 'System.Collections.Generic.List<ParserRuleContext>' 
to 'System.Collections.Generic.List<T>'

Given that List is limited to List <ParserRuleContext> by the where clause, I don’t understand this?

+3
source share
2 answers

Just because you know that for a specific Typeyou will store objects of that specific type in the ones List<ParserRuleContext>stored here 1 :

public Dictionary<Type, List<ParserRuleContext>> Contexts

There is not enough information for a type system that also knows this fact. As for this, each of these lists may contain all kinds of objects, all of which are derived from ParserRuleContext. Such a list, obviously, cannot be directly applied to any particular type of list.

() , . , List<TypeDerivedFromParserRuleContext> , List<TypeDerivedFromParserRuleContext> List<ParserRuleContext>.


1 , , , , " "

+4

, , , linq,

return Contexts[typeof(T)].Cast<T>();

return Contexts[typeof(T)].ToList<T>();
+6

All Articles