无法将类型'T'隐式转换为'T

时间:2013-02-11 23:33:21

标签: c# asp.net generics

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

1 个答案:

答案 0 :(得分:5)

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

T FetchAndCache()
{
     ...
}

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

一旦你这样做,编译器就会将T识别为在类中声明的那个。