通用方法总是返回NULL

时间:2019-04-17 13:00:36

标签: c# generics caching generic-method

我的项目中有一个通用方法(已经由另一位开发者开发),用于获取缓存;尽管我有键的值,但该方法仍返回NULL

请查看代码:

public static C GetFromCache<C>(string key) where C : class     
    {     
       if (cache != null)
       {
          var testCache = cache.Get(key); // This variable is getting results
          C p = cache.Get(key) as C; this point value of 'p' is NULL
          return p; 
        }

        return null;
    }

方法调用:

var lstCheck = ClassName.GetFromCache< List< int >(key);

Debugger screenshot

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为cache.Get(key)的结果不是 C类型。让我用代码解释一下:

Object name = "my-name";
var nameAsString = name as String; // name is already a String, so nameAsString = "my-name"
var nameAsRandom = name as Random; // name isn't Random, so nameAsRandom == null 

最好