C#读取泛型变量的值
泛型利于编写共用代码,但也有局限性,因为无法直接知道它的确切类型,更遑论读取里面的值。不过,利用反射,其实也能够读它的值。
话说,我有一段代码,对传过来的对象,希望判断它是否为空,或者里面是否有值。不为空,有值,才保存到缓存。不过这个对象是泛型变量。它对应的实际变量,常常是List对象。存入缓存之前,先判断是否Count() > 0。要实现此功能,需要读取其属性,看有没有一个名为Count的属性,有的话,是否大于0。
代码如下:
/*
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
*/
public async Task<T> StringGetShellAsync<T>(string key,Func<Task<T>> shell, TimeSpan? timeSpan = null)
{
/*
* 如果缓存中存在键值为key的值,则直接返回
* 否则调用shell获得该值,并以key为键值,存储于缓存;然后返回该值
* */
if (KeyExists(key))
{
return StringGet<T>(key);
}
else
{
var t = await shell();
if (needSave(t))
{
StringSet<T>(key, t, timeSpan);
}
return t;
}
}
private bool needSave<T>(T t)
{
bool yes = false;
if (t != null)
{
//这个泛型变量,常常是List对象。
PropertyInfo[] propertys = t.GetType().GetProperties();
PropertyInfo pi = propertys.Where(s => s.Name == "Count").FirstOrDefault();
if(pi != null && (int)pi.GetValue(t) > 0)
{
yes = true;
}
}
return yes;
}
我放下笃NET已经很久了,不过现在又捡起来。由于之前有一点积累,记忆一旦被唤醒,雄风犹在。
浙公网安备 33010602011771号