我正在为一个缓存提供程序编写流畅的注册,但不知何故我的泛型并不理想。我在这一部分遇到了错误:
value = _loadFunction();
。Cannot implicitly convert type 'T' to 'T [HttpRuntimeCache.cs(10)]
以下是代码:
using IDM.CMS3.Service.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
namespace IDM.CMS3.Web.Public.CacheProviders
{
public class HttpRuntimeCache<T> : IFluentCacheProvider<T>
{
string _key;
Func<T> _loadFunction;
DateTime? _absoluteExpiry;
TimeSpan? _relativeExpiry;
public HttpRuntimeCache()
{
}
public IFluentCacheProvider<T> Key(string key)
{
_key = key;
return this;
}
public IFluentCacheProvider<T> Load(Func<T> loadFunction)
{
_loadFunction = loadFunction;
return this;
}
public IFluentCacheProvider<T> AbsoluteExpiry(DateTime absoluteExpiry)
{
_absoluteExpiry = absoluteExpiry;
return this;
}
public IFluentCacheProvider<T> RelativeExpiry(TimeSpan relativeExpiry)
{
_relativeExpiry = relativeExpiry;
return this;
}
public T Value()
{
return FetchAndCache<T>();
}
public void InvalidateCacheItem(string cacheKey)
{
throw new NotImplementedException();
}
T FetchAndCache<T>()
{
T value;
if (!TryGetValue<T>(_key, out value))
{
value = _loadFunction();
if (!_absoluteExpiry.HasValue)
_absoluteExpiry = Cache.NoAbsoluteExpiration;
if (!_relativeExpiry.HasValue)
_relativeExpiry = Cache.NoSlidingExpiration;
HttpContext.Current.Cache.Insert(_key, value, null, _absoluteExpiry.Value, _relativeExpiry.Value);
}
return value;
}
bool TryGetValue<T>(string key, out T value)
{
object cachedValue = HttpContext.Current.Cache.Get(key);
if (cachedValue == null)
{
value = default(T);
return false;
}
else
{
try
{
value = (T)cachedValue;
return true;
}
catch
{
value = default(T);
return false;
}
}
}
}
}
HttpRuntimeCache<T>
类声明中相同名称的类型参数来遮蔽FetchAndCache<T>
中的一个。这些是不同的T
。看起来你并不真正需要在方法上重复类型参数。 - millimooseT FetchAndCache<T>
和bool TryGetValue<T>
正在重新定义一个新的T
类型。我认为,如果删除额外的泛型声明,它应该能正常工作。也就是说,将它们改写成T FetchAndCache()
和bool TryGetValue(...)
就可以了。 - Chris Sinclair