[英]Syntax: derived type, nested generics
I want to have a dictionary that maps from one generic type K<T>
to another generic type V<T>
. 我想拥有一个从一个通用类型K<T>
映射到另一个通用类型V<T>
的字典。 Note that type T
should be the same in both cases. 注意,在两种情况下,类型T
应该相同。 So I thought I would create a derived class from Dictionary<K,V>
with one more type argument, but I cannot find the right syntax. 所以我以为我会从Dictionary<K,V>
创建一个派生类Dictionary<K,V>
并带有一个更多的类型参数,但是我找不到正确的语法。
This is what I tried: 这是我尝试的:
1. 1。
class MyDictionary<T,K,V> : Dictionary<K<T>,V<T>> { ... }
// syntax error: The type parameter K cannot be used with type arguments.
// (same with V)
2. 2。
class MyDictionary<T,K<T>,V<T>> : Dictionary<K,V> { ... }
// many syntax errors: "," expected; "{" expected; ...
3. 3。
class MyDictionary<T,K,V> : Dictionary<K,V> { ... }
// works, but does not make the connection between K and T and between V and T
Maybe I can use some where clause? 也许我可以使用一些where子句?
Some examples for better understanding: 为了更好地理解一些示例:
MyDictionary<int,List,HashSet>
should essentially be Dictionary<List<int>,HashSet<int>>
. MyDictionary<int,List,HashSet>
本质上应该是Dictionary<List<int>,HashSet<int>>
。
MyDictionary<float,Queue,Stack>
should essentially be Dictionary<Queue<float>, Stack<float>>
. MyDictionary<float,Queue,Stack>
本质上应该是Dictionary<Queue<float>, Stack<float>>
。
Use generic type constraints ; 使用通用类型约束 ; based on your examples you might want to settle on some base class/interface for the two. 根据您的示例,您可能希望为两者确定一些基类/接口。 For example, the following would work for both of your cases: 例如,以下方法适用于您的两种情况:
class MyDictionary<T,K,V> : Dictionary<K,V>
where K : IEnumerable<T>
where V : IEnumerable<T>
If that's not viable, ie you need to be able to store mappings between, say, Action<String>
and IEqualityComparer<String>
, you won't be able to do that directly; 如果这不可行,即您需要能够存储Action<String>
和IEqualityComparer<String>
之间的映射,那么您将无法直接执行此操作。 you can at best settle for checking generic type parameters at runtime (eg in your the constructor for your class). 您最多可以在运行时检查通用类型参数(例如,在类的构造函数中)。
Seems you need something like this: 似乎您需要这样的东西:
class ClassK<T> { }
class ClassV<T> { }
class MyComplexDictionary<T> : Dictionary<K<T>, V<T>> { }
It will prevent you from adding incorrectly typed instances of K<> and V in compile time. 这将防止您在编译时添加类型错误的K <>和V实例。
var a = new MyComplexDictionary<string>();
a.Add(new ClassK<string>(), new ClassV<string>()); //works
a.Add(new ClassK<int>(), new ClassV<string>()); // compilation error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.