Classes génériques, réflexion
Bonjour a tous,
Je viens de tomber sur un problème assez important en commençant a toucher a la réflexion en C#, voici le contexte :
Le but de bout de code est de faire une interface de gestion des entrées / sorties de base (clavier, souris, manette ..).
Étant donne que ces 3 périphériques sont assez proches le code l'est aussi donc j'ai voulu utiliser un maximum de templates.
(Je développe sur XNA mais pour cet exemple j'ai fait sans).
J'ai donc 2 classes :
- LocalInputManager :
Se charge de stocker une liste de Control, de les modifier, supprimer, mettre en pause etc etc.
- Control :
Stock un groupe de touches liées a un évènements entre autre.
Voici un exemple :
LocalInputManager :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestReflection
{
public enum Keys
{
Left,
Right,
Up,
Down,
Space
};
class LocalInputManager<T, C> where C : class, new()
{
protected List<KeyValuePair<string, C>> controls;
private int totalControls;
public LocalInputManager()
{
this.totalControls = 0;
this.controls = new List<KeyValuePair<string, C>>();
}
public void AddControl(string Name, T Keys, bool KeyRepeat)
{
C instance = (C)Activator.CreateInstance(typeof(C), Keys, KeyRepeat);
this.controls.Add(new KeyValuePair<string, C>(Name, instance));
this.totalControls++;
}
public void UpdateAllControls()
{
for (int i = 0; i < this.totalControls; i++)
{
this.controls[i].Value.Update();
}
}
}
} |
Control :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestReflection
{
class Control<T>
{
private T controls;
private bool repeat;
public Control()
{
this.repeat = false;
}
public Control(T Key, bool Repeat)
{
this.controls = Key;
this.repeat = Repeat;
}
public void Update()
{
Console.WriteLine("Mise a jour effectuee.");
}
}
} |
Et un petit main de test qui expose le probleme :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestReflection
{
class Program
{
static void Main(string[] args)
{
LocalInputManager<Keys, Control<Keys>> manager;
manager = new LocalInputManager<Keys, Control<Keys>>();
manager.AddControl("Courir droite", Keys.Right, true);
manager.AddControl("Sauter", Keys.Space, false);
}
}
} |
Le problème se situe dans la classe LocalInputManager, dans la méthode UpdateAllControls.
En effet, il ne trouve pas la méthode Update() contenue dans C, ce en quoi j'ai du mal a lui en vouloir car C est un type générique.
Alors la question est : Comment lui préciser que C possède bel et bien la méthode sans préciser le type car il n'y a plus d'intérêt dans ce cas ?
Merci pour votre aide.