如何创建具有两个参数的泛型,其中第二个参数取决于第一个参数。在这种情况下,我将创建一个哈希类,在这里我需要对象的类型和标识它的密钥。
一些简化的代码进行解释:
class MyCache<T,Key> : where T is CommonImpl {
Dictionary<Key,T> cache;
T Get( Key v ) {
...
var newValue = new T(v);
return newValue;
}
}
class ImplA : CommonImpl {
public ImplA( String key ) { }
}
class ImplB : CommonImpl {
public ImplB( SomeType key ) { }
}
我在这里有两个使用此缓存MyCache<ImplA,String>
和MyCache<ImplB,SomeType>
。
我认为您要达到的目标是这样的:
public abstract class Base<TKey>
{
public Base(TKey key) { }
}
public class ImplA : Base<string>
{
public ImplA(string key) : base(key) {}
}
public class MyCache<TBase, TKey> where TBase : Base<TKey>
{
public TBase Get(TKey key)
{
return (TBase)Activator.CreateInstance(typeof(TBase), key);
}
}
然后你可以打电话
var b = new MyCache<ImplA, string>().Get("hi");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句