在我看来我应该能够做到这一点?但我不能。
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 被 where 子句限制为 List
最佳答案
我相信这应该是列表的实例与字典中的列表具有不同的提示,如果您使用 linq 进行转换就可以解决
return Contexts[typeof(T)].Cast<T>();
或
return Contexts[typeof(T)].ToList<T>();
关于c# - 泛型方法返回值的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21910525/