Sono un neofita dei generici in C# e sto cercando di creare una memoria che altre parti del mio programma possano richiedere per modelli oggetti. L'idea era che se la mia classe cache ha l'oggetto, controlla la sua data e la restituisce se l'oggetto non è più vecchio di 10 min. Se è più vecchio di 10 minuti, scarica un modello aggiornato dal server online. Non ha l'oggetto lo scarica e lo restituisce.Come posso creare una classe che memorizza nella cache gli oggetti?
Ma ho qualche problema ad associare i miei oggetti con un DateTime, rendendolo tutto generico.
// 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;
}
}
puoi fornire maggiori dettagli sul problema/errore nell'associare oggetti? probabilmente potresti provare la classe invece della struttura per 'DatedObject', e se non vuoi creare il tuo oggetto di classe, prova Tuple – Rex
[Akavache] (https://github.com/github/Akavache) potrebbe valere la pena in. –