2016-10-10 71 views
1

为什么这会给编译器带来错误?EventAggregator Helper通用方法

public class EventAggregationHelper { 

    public static SubscriptionToken SubscribeToEvent<T>(IEventAggregator eventAggregator) where T : EventBase { 

     T evt = eventAggregator.GetEvent<T>(); 
     //T evt = eventAggregator.GetEvent<T>(); 
     return null; 
    } 
} 

的错误是:

严重性代码说明项目文件的线路抑制状态 错误CS0310“T”必须是为了用它作为参数的非抽象类型具有公共的无参数的构造函数在通用类型或方法 'TEventType' 'IEventAggregator.GetEvent()' EntitySetGridTWPF d:\ DEVELOPER.NET \ COMERCIAL \ EntityBookCommon \ EntitySetGridTWPF \ EventAggregation \ EventAggregationHelper.cs 9主动

就行了:

T evt = eventAggregator.GetEvent<T>(); 

我以前用过这种方法调用其他泛型方法并且工作过。 GetEvent有什么特别之处?

在此先感谢。

+0

也许从阅读和理解错误的提示开始。 – kiziu

+0

@kiziu相信我,当我告诉你我在尝试搜索信息并尝试太多事情之前,在任何论坛上发问,包括这个。有时候每个人都有愚蠢的错误。 –

回答

2

IEventAggregator.GetEventnew()约束,这意味着你的订阅也需要添加new()约束,还需要由您的实现类T,其中必须有一个公共的无参数(默认)构造函数(且不得为满足摘要)。

public static SubscriptionToken SubscribeToEvent<T> 
      (IEventAggregator eventAggregator) where T : EventBase, new() { 
+0

我也添加了new(),但是当我强制将EventBase强制为EventBase时,我不是添加了new(),而是将其添加到PubSubEvent中,所以这一定是为什么它一开始就不起作用,然后我感到困惑。非常感谢你。 –