如何重写这种获取泛型存储库以使用泛型的方法
本文关键字:泛型 存储 方法 获取 何重写 重写 | 更新日期: 2023-09-27 18:29:08
我有一个从字典中获取通用存储库的方法:
public readonly IDictionary<Type, IRepository> _repositories = new Dictionary<Type, IRepository>();
public IRepository GetRepository(Type type)
{
if (this._repositories.ContainsKey(type)) {
return this._repositories[type];
}
return null;
}
这很有效,但我希望它能使用泛型,所以我尝试了:
public IRepository<T> GetRepository<T>() where T : class
{
var typeParameterType = typeof(T);
if (this._repositories.ContainsKey(typeParameterType)) {
return this._repositories[typeParameterType];
}
return null;
}
但我收到了一个错误,比如"无法将类型IRepository
隐式转换为IRepository<T>
"。存在显式转换(是否缺少强制转换?)
有人知道如何解决这个问题吗?
如错误所示,您需要将GetRepository
的返回类型更改为非通用IRepository
:
public IRepository GetRepository<T>() where T : class
{
var typeParameterType = typeof(T);
if (this._repositories.ContainsKey(typeParameterType))
return this._repositories[typeParameterType];
return null;
}
或者,简单地将this._repositories
的返回强制转换为泛型类型IRepository<T>
:
public IRepository<T> GetRepository<T>() where T : class
{
var typeParameterType = typeof(T);
if (this._repositories.ContainsKey(typeParameterType))
return this._repositories[typeParameterType] as IRepository<T>;
return null;
}
或者可能更合适:
public IRepository<T> GetRepository<T>() where T : class
{
Repository<T> rep = null;
this._repositories.TryGetValue(typeof(T), out rep);
return rep;
}
您的字典有一种IRepository类型。因此,当你撤回一个元素时,它也有这种类型。另一方面,您的方法希望您返回类型为IRepository<T>
的值。
有两种方法可以解决这个问题。将方法的返回类型更改为IRepository,或者在返回元素之前将其转换为IRepository<T>
:
return (IRepository<T>)this._repositories[typeParameterType];
将返回类型从IRepository<T>
更改为简单的IRepository
,以匹配原始非泛型方法的返回类型。
返回类型应该是IRepository
(注意缺少<T>
),因为IRepository在字典的定义中不是通用的。