泛型方法总是返回 NULL
Generic Method always returning NULL
我的项目中有一个通用方法(已经由另一位开发人员开发)用于获取缓存;虽然我有键值,但方法仍然 returns 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
发生这种情况是因为 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
最佳,
我的项目中有一个通用方法(已经由另一位开发人员开发)用于获取缓存;虽然我有键值,但方法仍然 returns 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
发生这种情况是因为 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
最佳,