Please have a look at code below, which is based on the assumption that you have a controller class Controller. It is a generic class with constraint CGeneric where T:IRecord, two concrete record classes CRecordCustomer:IRecord, and CRecordVipCustomer:Irecord. The question is how to attach event handler to a generic type without knowing type of t before runtime?
public class CGeneric<T> where T:IRecord, new()
{
public delegate void OnCompleted();
public event OnCompleted completed;
private void ProcessStuff(T ConcreteRecordType)
{
T concreteInstance = default(T);
(concreteInstance as T).DoSomeInterfaceStuff();
if(this.completed !=null)
{
this.completed;
}
}
}
// This is how the controller class instantiates CGeneric<T>
// Using reflection gets all types that implement IRecord
// Then using one of those types (which is unknown at compile time):
class Controller
{
Type[] allTypes = Assembly.GetExecutingAssembly().GetTypes();
Type concreteType allTypes.Where(t => t.GetInterfaces().Contains(typeof(IRecord)) && !IgnoreType(t)).ToList()[0];
Type genericType = typeof(CGeneric<>);
genericType = genericType .MakeGenericType(
ConstructorInfo constructor = genericType .GetConstructor(new Type[] { });
Object genericInstance = constructor.Invoke(new Object[] { });
//This is where I need to hook to OnCompletedEvent
MethodInfo processmoethod = genericType .GetMethod("Process");
processmoethod.Invoke(genericInstance , concreteType );
}