我想創建簡單的快取管理器(用于 Redis),它回傳值通用型別T但是當我從 Redis 反序列化值時出現錯誤cannot convert source type T? to target type T?
public class InMemoryCacheService<T> : ICacheService<T>
{
private T? cacheValue = default(T?);
public async Task<T> GetValueAsync<T>(string key, Expression<T> expression)
{
GetCacheGalueAsync<T>(key);
//code where I check if cacheValue is null get value from DB
}
public void GetCacheGalueAsync<T>(string key)
{
string value = _distributedCache.GetString(key);
if (value is not null)
{
T? t = JsonSerializer.Deserialize<T>(value);
//cannot convert source type T? to target type T?
cacheValue = t;
}
}
}
uj5u.com熱心網友回復:
這里呼叫了兩個不同的型別引數T。一種是在泛型型別宣告中:
public class InMemoryCacheService<T>
另一個在泛型方法宣告中:
public void GetCacheGalueAsync<T>(string key)
如果您將它們分別重命名為TClassand TMethod,您將看到不同的錯誤訊息,轉換TMethod?為TClass?.
我強烈懷疑你只是想讓你的方法非泛型:
public void GetCacheValueAsync(string key)
這種方式T只會參考類宣告的型別引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/442705.html
