c# - 泛型方法返回值的类型

标签 c# generics

在我看来我应该能够做到这一点?但我不能。

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/

相关文章:

c# - SDK 路径在 Notepad++ plugin.net 中为空

c# - mvc 中的自定义错误处理不起作用

swift - 如何在 Swift 中创建接受 Double 和 Int 的泛型类

java - 在 Java 语法中,Class<?扩展一些东西>

javascript - 使管道的转换方法中的返回语句通用

c# - 按字符串给定的类型获取对象列表

c# - 单个数据库和多个用户桌面应用程序

c# - 描述 ASMX 网络服务 WebMethod 参数

c# - 如何在 Debug模式下跳出 foreach 循环

c# - 是否可以从成员中生成通用返回类型