I just found a fairly significant problem beginning to touch the reflection in C#, here's the context:
The purpose piece of code is to make an interface for managing I/O base (keyboard, mouse, joystick ..). Since these 3 devices are close enough the code is so I wanted to use a maximum of templates.
(I developed on XNA but for this example I did not).
So I have 2 classes:
- LocalInputManager: Undertakes to store a list of Control, modify, delete, pause etc etc.
- Control: Stock a group of keys associated with an event from another.
Here's an example:
LocalInputManager:
Code:
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:
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("Updated." );
}
}
}
And a small hand to test that exposes the problem:
Code:
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("Running Right", Keys.Right, true);
manager.AddControl("Skip", Keys.Space, false);
}
}
}
The problem lies in the class LocalInputManager in UpdateAllControls method.
Indeed, it is not the method Update () contained in C, how hard I was angry with him because C is a generic type.
So the question is: How to specify that C does have the method without specifying the type as there is more interest in this case?
Bookmarks