[英]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.