【发布时间】:2013-01-29 10:43:54
【问题描述】:
请看下面的代码,这是基于你有一个控制器类 Controller 的假设。它是一个具有约束 CGeneric 的泛型类,其中 T:IRecord、两个具体的记录类 CRecordCustomer:IRecord 和 CRecordVipCustomer:Irecord。问题是如何在运行前不知道 t 类型的情况下将事件处理程序附加到泛型类型?
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 );
}
【问题讨论】:
-
你试过编译这段代码吗?
标签: c# reflection delegates event-handling generic-programming