如何在 where 子句中使用泛型创建泛型方法? (像泥一样清澈的人!)
有没有办法做到这一点:
protected void SubscribeToEvent<TEvent, TPayload>(Action<TPayload> a_action)
where TEvent : CompositePresentationEvent<TPayload>
{
TEvent newEvent = _eventAggregator.GetEvent<TEvent>();
SubscriptionToken eventToken = newEvent.Subscribe(a_action);
_lstEventSubscriptions.Add(new KeyValuePair<EventBase, SubscriptionToken>(newEvent, eventToken));
}
不需要用户指定 TPayload
参数?
Is there a way of doing this:
protected void SubscribeToEvent<TEvent, TPayload>(Action<TPayload> a_action)
where TEvent : CompositePresentationEvent<TPayload>
{
TEvent newEvent = _eventAggregator.GetEvent<TEvent>();
SubscriptionToken eventToken = newEvent.Subscribe(a_action);
_lstEventSubscriptions.Add(new KeyValuePair<EventBase, SubscriptionToken>(newEvent, eventToken));
}
without requiring the user to specify a TPayload
parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有。 C# 4 中不行。您无法使用单一方法来做到这一点。
无法从传递给方法的参数推断出 TEvent,并且由于部分推断不适用于泛型类型参数,因此您必须在调用站点手动指定类型参数。
No, there isn't. Not in C# 4. You can't do that with a single method.
TEvent
cannot be inferred from the arguments passed to the method, and since partial inference is not available for generic type arguments, you'll have to manually specify the type argument at call site.不管你相信与否,VB.NET 的扩展方法 与此非常相似。
假设我有以下扩展方法:
那么我实际上可以调用此方法,传递单个类型参数,仅适用于
T
,并推断出TInferred
:输出:
遗憾的是,正如 Mehrdad 所指出的,这在 C# 中是不可能的。
Believe it or not, VB.NET has something very much like this for extension methods.
Say I have the following extension method:
Then I could actually call this method passing a single type parameter, for
T
only, withTInferred
being inferred:Output:
Sadly, as Mehrdad has indicated, this is not possible in C#.