订阅动态类型列表
Subscribe to a list of dynamic types
我在我的程序中使用 Messenger,具有订阅和发布方法。
我想订阅特定对象的消息类型列表(实现接口 "IMessage")。
所以,我有一个订阅方法。
它应该是这样的:
subscribe(List<T> listMessagesTypes)
{
foreach(IMessage messageType in listMessagesTypes)
_messenger.subscribe<messageType>(doAction);
}
当然,这不行
我无法在任何地方定义列表应仅包含实现接口 IMessage
的类型
messageType 是对象,不是类型。我的代码有语法错误!
有人知道我该如何处理吗?
您不能使用通用订阅方法,除非它的类型在编译时已知。
https://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx
你可以试试:
void subscribe(List<Type> listMessagesTypes, Action doAction)
{
foreach (Type messageType in listMessagesTypes)
if (typeof(IMessage).IsAssignableFrom(messageType)
_messenger.subscribe(messageType, doAction);
}
但是你仍然需要实现一个接受类型的订阅方法。
您可以使用反射订阅多种类型:
// You need to change List<T> to List<Type>, and you need to only pass types here
public void subscribe(List<Type> listMessagesTypes)
{
foreach(Type messageType in listMessagesTypes)
{
// find method "subscribe" on Messenger type
MethodInfo method = typeof(Messenger).GetMethod("subscribe");
// create a generic definition of method with specified type
MethodInfo genericMethod = method.MakeGenericMethod(messageType);
// invoke this generic method
// the assumption is that your method signature is like this: doAction(IMessage message)
genericMethod.Invoke(_messenger, new object[] { new Action<IMessage>(doAction)});
}
}
该方法将像这样调用:
var listOfTypes = new List<Type>{ typeof(MessageA), typeof(MessageB)};
subscribe(listOfTypes);
我在我的程序中使用 Messenger,具有订阅和发布方法。 我想订阅特定对象的消息类型列表(实现接口 "IMessage")。 所以,我有一个订阅方法。 它应该是这样的:
subscribe(List<T> listMessagesTypes)
{
foreach(IMessage messageType in listMessagesTypes)
_messenger.subscribe<messageType>(doAction);
}
当然,这不行
我无法在任何地方定义列表应仅包含实现接口 IMessage
的类型
messageType 是对象,不是类型。我的代码有语法错误!
有人知道我该如何处理吗?
您不能使用通用订阅方法,除非它的类型在编译时已知。 https://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx
你可以试试:
void subscribe(List<Type> listMessagesTypes, Action doAction)
{
foreach (Type messageType in listMessagesTypes)
if (typeof(IMessage).IsAssignableFrom(messageType)
_messenger.subscribe(messageType, doAction);
}
但是你仍然需要实现一个接受类型的订阅方法。
您可以使用反射订阅多种类型:
// You need to change List<T> to List<Type>, and you need to only pass types here
public void subscribe(List<Type> listMessagesTypes)
{
foreach(Type messageType in listMessagesTypes)
{
// find method "subscribe" on Messenger type
MethodInfo method = typeof(Messenger).GetMethod("subscribe");
// create a generic definition of method with specified type
MethodInfo genericMethod = method.MakeGenericMethod(messageType);
// invoke this generic method
// the assumption is that your method signature is like this: doAction(IMessage message)
genericMethod.Invoke(_messenger, new object[] { new Action<IMessage>(doAction)});
}
}
该方法将像这样调用:
var listOfTypes = new List<Type>{ typeof(MessageA), typeof(MessageB)};
subscribe(listOfTypes);