我有一个泛型类A,另一个类B处理A的实例并包含一些额外的数据.我需要有两个单独的类.B不能从A继承,因为A有其他衍生物,B需要包含对A的引用.
举个简单的例子,我想写的是(字典是A,dicthandler是B):
class dicthandler<T> where T : Dictionary<Tk, Tv>
Run Code Online (Sandbox Code Playgroud)
但它不编译,我需要指定所有类型参数:
class dicthandler<T, Tk, Tv> where T : Dictionary<Tk, Tv>
Run Code Online (Sandbox Code Playgroud)
但实际上我并不关心Tk和Tv是什么,所以它们完全是多余的,我只需要T.每当我想创建一个新实例时,我需要为构造函数指定所有类型参数,这会伤害我.
显然我需要一些技巧.有任何想法吗?
不,没有办法做到这一点.任何情况下DictHandler
必须知道的确切类型T
,包括的类型TKey
和TValue
.
如果您实际拥有相关字典的实例,则可以使用类型推断来减少显式指定类型参数的频率.例如:
public static class DictHandler
{
public static DictHandler<T, TKey, TValue> CreateHandler<T, TKey, TValue>
(T dictionary1, Dictionary<TKey, TValue> dictionary2)
where T : Dictionary<TKey, TValue>
{
return new DictHandler<T, TKey, TValue>();
}
}
public class DictHandler<T, TKey, TValue> where T : Dictionary<TKey, TValue>
{
}
Run Code Online (Sandbox Code Playgroud)
然后像这样创建它:
Dictionary<string, int> dict = new Dictionary<string, int>();
var handler = DictHandler.CreateHandler(dict, dict);
Run Code Online (Sandbox Code Playgroud)
我相信你必须拥有这两个参数的原因是,参数(在类型推断中使用的所有参数)最终与直接提及类型参数的参数相对应.我不完全确定 - 这肯定有些难看.
另一种方法是为A创建一个非通用的基本类型或基本接口.例如,在这种情况下(假设我们可以控制字典)我们创建:
public interface INonGenericDictionary
{
// Members which don't rely on the type parameters
}
public class Dictionary<TKey, TValue> : INonGenericDictionary
{
...
}
Run Code Online (Sandbox Code Playgroud)
然后
public class DictHandler<T> where T : INonGenericDictionary
{
...
}
Run Code Online (Sandbox Code Playgroud)
我们无法确定这是否适用于您的情况,但它可能是.
归档时间: |
|
查看次数: |
404 次 |
最近记录: |