简体   繁体   中英

Type of generics method return value

It seems to me like I should be able to do this? But I can't.

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

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

This produces the error:

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

Given that List is constrained to be List<ParserRuleContext> by the where clause, I don't understand this?

I believe that should be the fact that the instance of the list being with a different tipage the list in the dictionary, if you make a cast with linq is to solve

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

or

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

Just because you know that, for a particular Type , you're only going to store objects of that specific type in the List<ParserRuleContext> stored here 1 :

public Dictionary<Type, List<ParserRuleContext>> Contexts

There's not enough information for the type system to also know that fact. So far as it's concerned, each of those lists could contain all kinds of objects, all deriving from ParserRuleContext . Such a list obviously couldn't be directly cast to any more specific type of list.

And generic types don't (generally) mirror any inheritence structure that their type parameters do. So it's not like you might have stored a List<TypeDerivedFromParserRuleContext> in this dictionary - because List<TypeDerivedFromParserRuleContext> doesn't inherit from List<ParserRuleContext> .


1 At least, I assume that that's the assumption by which you believe that the rest of this code "made sense"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM