我正在为缓存提供程序编写流利的注册,但由于某种原因,我的泛型并不满意。我在这一点上遇到错误: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;
}
}
}
}
}