我正在尝试包装对 Events 的访问来自 EventAggregator Prism 的可重用性
这是一个示例代码
protected void Subscription<T1,T2>(Action<T2> OnSubcribe) where T1:CachedEvent<T2>
{
T1 @event = _eventAggregator.GetEvent<T1>();
event.Subcribe(OnSubcribe,true);
//Some Codes other codes
}
我在 T1
上设置了约束条件, CachedEvent
,它是 PubSubEvent<TPayload>
的非抽象派生类
但是还是报错
'T1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter....
假设这在 C# 中不是真的有效,还有其他替代方案吗?
更新:
这是我到目前为止所做的
我做了@event
一个参数
protected void Subscription<T1,T2>(T1 @event, Action<T2> OnSubcribe) where T1:CachedEvent<T2>
{
@event.Subcribe(OnSubcribe,true);
//Some Codes other codes
}
我的应用程序可以运行,但我仍然无法摆脱创建 @event
的锅炉点, 调用 GetEvent
手动,每次我调用Subscription
例子:
Subcription(eventAggregator.GetEvent<SomeEventBasedOnCachedEvent>(),AMethodDoneOnSubcribe);
最佳答案
我一直想念的是 new()
通用类型的约束 T1
.
显然 GetEvent<T>
Prism IEventAggregator要求 T
必须有一个无参数的构造函数。
protected void Subscription<T1,T2>(Action<T2> OnSubcribe) where T1:CachedEvent<T2>,new()
{
T1 @event = _eventAggregator.GetEvent<T1>();
event.Subcribe(OnSubcribe,true);
//Some Codes other codes
}
关于c# - 为 Prism Eventaggregator WPF 使用通用的 PubSubEvents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49895195/