Le code suivante se compose deux cours:Comment puis-je forcer un constructeur C# à être une usine?
- SmartForm (classe simple modèle)
- SmartForms (classe plurielle qui contient une collection de SmartForm objets)
Je veux être capable d'instancier à la fois les classes au singulier et au pluriel comme ça (c.-à-d. Je ne veux pas une méthode de fabrication GetSmartForm()):
SmartForms smartForms = new SmartForms("all");
SmartForm smartForm = new SmartForm("id = 34");
Pour consolider la logique, seule la classe plurielle devrait accéder à la base de données. La classe singulière, lorsqu'on lui demande de s'instancier, instanciera simplement une classe plurielle, puis choisira l'objet parmi la collection de l'objet pluriel et deviendra cet objet.
Comment faire cela? J'ai essayé d'assigner l'objet à this
qui ne fonctionne pas.
using System.Collections.Generic;
namespace TestFactory234
{
public class Program
{
static void Main(string[] args)
{
SmartForms smartForms = new SmartForms("all");
SmartForm smartForm = new SmartForm("id = 34");
}
}
public class SmartForm
{
private string _loadCode;
public string IdCode { get; set; }
public string Title { get; set; }
public SmartForm() {}
public SmartForm(string loadCode)
{
_loadCode = loadCode;
SmartForms smartForms = new SmartForms(_loadCode);
//this = smartForms.Collection[0]; //PSEUDO-CODE
}
}
public class SmartForms
{
private string _loadCode;
public List<SmartForm> _collection = new List<SmartForm>();
public List<SmartForm> Collection
{
get
{
return _collection;
}
}
public SmartForms(string loadCode)
{
_loadCode = loadCode;
Load();
}
//fills internal collection from data source, based on "load code"
private void Load()
{
switch (_loadCode)
{
case "all":
SmartForm smartFormA = new SmartForm { IdCode = "customerMain", Title = "Customer Main" };
SmartForm smartFormB = new SmartForm { IdCode = "customerMain2", Title = "Customer Main2" };
SmartForm smartFormC = new SmartForm { IdCode = "customerMain3", Title = "Customer Main3" };
_collection.Add(smartFormA);
_collection.Add(smartFormB);
_collection.Add(smartFormC);
break;
case "id = 34":
SmartForm smartForm2 = new SmartForm { IdCode = "customerMain2", Title = "Customer Main2" };
_collection.Add(smartForm2);
break;
default:
break;
}
}
}
}
Exactement, je cherche quelque chose comme ça, tout ce dont j'ai besoin sont des propriétés simples, mais il faut que ce soit dynamique pour tout type d'objet, je pense à une classe de "clonage par réflexion", isn ' t-il quelque chose comme ça, par exemple System.Reflection.Clone (smartForms [0])? –