Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Reflection;
- using ConsoleApplication1;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Persistable c = new PersistableObjects.Customer(1, "C");
- Persistable e = new PersistableObjects.Employee();
- Persistence.PrintPersistedObjects();
- Console.ReadLine();
- }
- }
- interface Persistable
- {
- object GetID();
- }
- static class Persistence
- {
- public static Type[] persistableEntities = AppDomain.CurrentDomain.GetAssemblies()
- .SelectMany(t => t.GetTypes())
- .Where(t => t.IsClass && t.Namespace == "PersistableObjects").ToArray();
- static Dictionary<Type, Dictionary<object, Persistable>> topkek = new Dictionary<Type,Dictionary<object, Persistable>>();
- static Persistence()
- {
- foreach (Type t in persistableEntities)
- {
- topkek.Add(t, new Dictionary<object, Persistable>());
- }
- }
- public static void Persist(this Persistable persistable)
- {
- topkek[persistable.GetType()].Add(persistable.GetID(), persistable);
- }
- public static void PrintPersistedObjects()
- {
- foreach (var v in topkek.Values)
- {
- foreach (Persistable p in v.Values)
- {
- //Console.WriteLine(p.GetType());
- if (persistableEntities.Contains(p.GetType()))
- {
- foreach (FieldInfo f in p.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
- {
- object fieldValue;
- if (persistableEntities.Contains(f.FieldType))
- {
- fieldValue = ((Persistable)f.GetValue(p)).GetID();
- Console.WriteLine(fieldValue);
- }
- else
- {
- fieldValue = f.GetValue(p);
- Console.WriteLine(fieldValue);
- }
- }
- }
- }
- }
- }
- }
- }
- namespace PersistableObjects
- {
- class Customer : Persistable
- {
- private int id;
- private string name;
- public Customer(int id, string name)
- {
- this.id = id;
- this.name = name;
- this.Persist();
- }
- public object GetID()
- {
- return id;
- }
- }
- class Employee : Persistable
- {
- private int id = 2;
- private string name = "E";
- private Customer c;
- public Employee()
- {
- c = new Customer(3, "FU");
- this.Persist();
- }
- public object GetID()
- {
- return id;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement