Hook up events + reflection
Følgende kode starter tClass x antal gange via reflection, men hvordan får jeg forbundet events fra classen, i dette test tilfælde her skal tClass udføre et job og kalde et event når job er udført.public class Program
{
static void Main(string[] args)
{
var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
for (int i = 0; i <= 2; i++ )
{
Console.WriteLine("tClass initialize {0}", i);
Type _classType = typeof(tClass);
var _classInstance = (object)Activator.CreateInstance(_classType);
MethodInfo mInfo = _classType.GetMethod("start");
mInfo.Invoke(_classInstance, null);
}
Console.WriteLine();
Console.ReadLine();
}
public void tClass_completed(Guid guid)
{
Console.WriteLine("tClass {0} completed", guid);
}
}
public class tClass
{
public delegate void tClass_completed(Guid guid);
public event tClass_completed event_tClassCompleted;
private Guid guid;
public tClass()
{
guid = Guid.NewGuid();
Console.WriteLine("tClass loaded {0}", guid);
}
public void start()
{
int _totalRuns = 5;
for (int i = 0; i <= _totalRuns; i++)
{
Console.WriteLine("tClass working hard {0}/{1}", i, _totalRuns);
System.Threading.Thread.Sleep(100);
}
if (event_tClassCompleted != null) event_tClassCompleted(guid);
}