【发布时间】:2015-10-21 14:02:47
【问题描述】:
我正在尝试在 PRISM 框架中重构我的一些方法,但并没有真正奏效。
我需要通过EventAggregator 发布消息,并且我编写了一个反射方法,它将查看包含Types 的List<Parameters> 并从这里发送消息。
但它从不发送任何消息。
原来安全广播as PubSubEvent<object>和public class Input: PubSubEvent<Output> {}不一样,这意味着returnObj?.Publish(data);是null,不会被调用。
public struct Parameters
{
public string Topic;
public Type Input;
public Type Output;
}
private List<Parameters> _list;
...
void SomeFunction()
{
_list.ForEach(m =>
{
var data = JsonConvert.DeserializeObject(dataString, m.Output);
var eventAggType = _eventAggregator.GetType();
var eventMethod = eventAggType.GetMethod("GetEvent");
var genericMethod = eventMethod.MakeGenericMethod(m.Input);
var returnObj = genericMethod.Invoke(_eventAggregator, null) as PubSubEvent<object>;
returnObj?.Publish(data);
// var datType = returnObj.GetType();
// if (datType.BaseType.Name == typeof (PubSubEvent<object>).Name)
// {
// var obj = Convert.ChangeType(returnObj, datType);
// ((PubSubEvent<object>) obj).Publish(data);
// }
}
}
我试图通过查看它实际输出的类型来修改代码(删除as PubSubEvent<object>),它是相同的BaseType。
但是转换为基本的PubSubEvent 并不是程序乐于看到的。
Exception thrown: 'System.InvalidCastException' in MyProject.ModuleA.dll
EXCEPTION: Unable to cast object of type 'MyProject.ModuleA.GlobalEvents.EventA' to type 'Microsoft.Practices.Prism.PubSubEvents.PubSubEvent`1[System.Object]'.
我如何Publish 使用正确的类型?
如果您知道自己在处理哪些类,它应该如下所示:
_eventAggregator.GetEvent<EventA>().Publish(data);
【问题讨论】:
标签: c# reflection prism eventaggregator