3

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

1 回答 1

5

T FetchAndCache<T>bool TryGetValue<T>正在重新定义一种与在类级别声明的类型不同的新类型。 T我认为一旦您删除了额外的通用声明,它应该可以正常工作。也就是说,将它们重写为:

T FetchAndCache()
{
     ...
}

bool TryGetValue(string key, out T value)
{
     ...
}

一旦你这样做了,编译器将把T这里识别为在类上声明的那个。

于 2013-02-11T23:45:53.877 回答