gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:00:58 25 4
gpt4 key购买 nike

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

最佳答案

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

T FetchAndCache()
{
...
}

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

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

关于c# - 无法将类型 'T' 隐式转换为 'T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14822942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com