c# - 为什么 C# 不支持泛型的泛型(具有参数化类型的泛型)?

标签 c# .net generics generic-collections nested-generics

最近(可能是设计缺陷)当需要收集 MyType<T> 时,我遇到了一项常规任务。其中 T不是固定的(即在一个集合中有多个不同的泛型实例化)。

由于广泛建议(对于这种情况),声明了一个抽象类:

public abstract class MyType {}
public class MyType<T>: MyType {}

然后我收集了 MyType . 然而,对于这个集合,我有一个限制,即任何类型的元素都不能超过一个 T .

因此,我对 ICollection<TBase> 做了一些自定义实现. 我想在那里包含一个方法 Get<TParam>()用于获取对应于类型 TParam 的项目.以后像这样使用:

MyCollection<MyType> collection = new MyCollection<MyType>();
MyType<int> myInt = collection.Get<int>();

然而我却意外的发现,我连声明都不会:

public TCustom<TParam> Get<TParam, TCustom<TParam>>() { } //this won't compile

因为 C# 和 .NET 都不支持内部泛型(或所谓的“泛型的泛型”)(我想)。您认为这些限制背后是否有任何具体原因(复杂性除外)?

UPDATE 1.询问编译器版本和编译器错误。

Microsoft C#、.NET 3.5(Visual Studio 2010)。 错误:

error CS0081: Type parameter declaration must be an identifier not a type

error CS0246: The type or namespace name 'TCustom' could not be found (are you missing a using directive or an assembly reference?)

更新 2. 问我是否需要修复或解释原因。我真的很想知道为什么。不过如果你有很好的解决问题的方法,也欢迎。

更新 3. 该问题可能已在 this blog post 中得到解答。 .看来 CLR 团队承受着巨大的压力,不能让语言过于复杂。

最佳答案

在这种情况下,您可以简单地将数据隐藏在非通用字典中:

private Dictionary<Type, object> _Data;

然后是您的 Get 方法:

public MyType<TParam> Get<TParam>()
{ 
    return (MyType<TParam>)_Data[typeof(TParam)];
}

如果 TParam 类型不相关,则没有通用的数据结构无论如何都会为您提供类型安全,那为什么还要尝试呢?

关于c# - 为什么 C# 不支持泛型的泛型(具有参数化类型的泛型)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7685150/

相关文章:

c# - 如何在 visual studio webtest 中将图像作为字节数组发布

.net - Silverlight 3 离线模式

Java泛型通配符问题

c# - 提交后 IEnumerable 属性为空

C# Winform( Entity Framework )- 将数据绑定(bind) DataGridView 或 BindingSource 转换为 DataTable

.net - 为 Windows 窗体应用程序选择字体

.net - debug.write 和 Trace.write 有什么区别?

java - 在 Java 中保留泛型的封装

typescript - 基于泛型的类字段类型

c# - 在Elastic Search NEST Client 6.X中的特定字段中使用动态字符串数组进行搜索