简体   繁体   English

泛型方法的类型返回值

[英]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? 鉴于List被子句限制为List <ParserRuleContext>,我不明白这一点?

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

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 : 仅仅因为知道,对于特定Type ,您只需要在此处存储的List<ParserRuleContext>存储特定类型的对象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 . 就它而言,每个列表都可以包含所有类型的对象,所有对象都来自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> . 因此,您可能在此字典中存储了List<TypeDerivedFromParserRuleContext> ,因为List<TypeDerivedFromParserRuleContext>不会从List<ParserRuleContext>继承。


1 At least, I assume that that's the assumption by which you believe that the rest of this code "made sense" 1至少,我认为这是你认为其余代码“有意义”的假设

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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