无法转换源类型 T?以 T 型为目标?

Cannot convert source type T? to target type T?

我想创建简单的缓存管理器(用于 Redis)return 值泛型类型 TO 但是当我从 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;
      }
   }
}


这里有两个不同类型的参数,叫做 T。一种是在通用 type 声明中:

public class InMemoryCacheService<T>

另一个在泛型方法声明中:

public void GetCacheGalueAsync<T>(string key)

如果将它们分别重命名为 TClassTMethod,您将看到不同的错误消息,将 TMethod? 转换为 TClass?

我强烈怀疑你只是想制作你的方法non-generic:

public void GetCacheValueAsync(string key)

这样 T 将只引用 class 声明的类型参数。