我是 C# 中的泛型新手,我正在尝试创建一个存储,我的程序的其他部分可以请求模型对象。这个想法是,如果我的缓存类有对象,它会检查它的日期并在对象不超过 10 分钟时返回它。如果它早于 10 分钟,它会从服务器在线下载更新的模型。它没有对象是下载它并返回它。
但是我在将我的对象与 DateTime 配对时遇到了一些问题,这一切都是通用的。
// model
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
Cache c = new Cache();
p = c.Get<Person>(p);
}
}
public class Cache
{
struct DatedObject<T>
{
public DateTime Time { get; set; }
public T Obj { get; set; }
}
List<DatedObject<T>> objects;
public Cache()
{
objects = new List<DatedObject<T>>();
}
public T Get<T>(T obj)
{
bool found = false;
// search to see if the object is stored
foreach(var elem in objects)
if( elem.ToString().Equals(obj.ToString() ) )
{
// the object is found
found = true;
// check to see if it is fresh
TimeSpan sp = DateTime.Now - elem.Time;
if( sp.TotalMinutes <= 10 )
return elem;
}
// object was not found or out of date
// download object from server
var ret = JsonConvert.DeserializeObject<T>("DOWNLOADED JSON STRING");
if( found )
{
// redate the object and replace it in list
foreach(var elem in objects)
if( elem.Obj.ToString().Equals(obj.ToString() ) )
{
elem.Obj = ret;
elem.Time = DateTime.Now;
}
}
else
{
// add the object to the list
objects.Add( new DatedObject<T>() { Time = DateTime.Now, Obj = ret });
}
return ret;
}
}