[英]C# equivalent of Java's List<? extends MyFancyClass>
I don't believe I saw this anywhere (I'm not sure how to word the question really so that may be why) so if it's already been answered I apologise. 我不相信我在任何地方都看到了这一点(我不确定该如何真正表达这个问题,所以可能是为什么),所以,如果已经回答了,我表示歉意。
I'm currently writing an application that has an event API that third parties can hook into, below is the code I'm using to fire the events. 我目前正在编写一个具有事件API的应用程序,第三方可以将其插入其中,以下是我用来触发事件的代码。
// Events.cs from the API project
public interface IEventListener
{
void Handle(IEvent @event);
}
public abstract class EventManager
{
public abstract void Register(PluginBase plugin, IEventListener listener);
public abstract void Call(IEvent @event);
}
// Events.cs from the main project
public class SimpleEventManager : EventManager
{
private readonly Dictionary<PluginBase, List<IEventListener>> _events =
new Dictionary<PluginBase, List<IEventListener>>();
public override void Register(PluginBase plugin, IEventListener listener)
{
}
public override void Call(IEvent @event)
{
// Iterate through _events.Values and call Handle on each IEventListener
}
}
Whilst the code above works fine I find how third parties hook into it to be incredibly ugly and was wondering if it would be possible to hook it up to use the Action
class. 尽管上面的代码可以正常工作,但是我发现第三方如何将其钩入极其丑陋的位置,并想知道是否有可能将其连接起来以使用Action
类。
// TestPlugin.cs
class MyTestPlugin : PluginBase
{
var handler = new MyEventHandler();
App.Instance.EventManager.Register(this, handler);
}
class MyEventHandler : IEventListener
{
public void Handle(IEvent @event)
{
if(@event is SomeEvent) HandleSomeEvent((SomeEvent) @event);
}
private void HandleSomeEvent(SomeEvent someEvent)
{
// Handle the event of course
}
}
My goal is to change the Register method to accept a third parameter, Action<IEvent>
though I've found out that if I reference a method then it must strictly accept an IEvent as an argument. 我的目标是更改Register方法以接受第三个参数Action<IEvent>
尽管我发现如果我引用一个方法,则它必须严格接受IEvent作为参数。 In Java you can use <? extends BaseClass>
在Java中,您可以使用<? extends BaseClass>
<? extends BaseClass>
(self explanatory), is there something like Action<? : IEvent>
<? extends BaseClass>
(自我解释),是否有类似Action<? : IEvent>
Action<? : IEvent>
or is this simply not possible? Action<? : IEvent>
还是这根本不可能?
This feature is called "generic constraints". 此功能称为“通用约束”。 You'd express it like this: 您可以这样表达:
public interface IEventListener<TEvent> where TEvent: IEvent
{
void Handle(TEvent @event);
}
class MyEventHandler : IEventListener<SomeEvent>
{
public void Handle(SomeEvent @event)
{
// Handle the event of course
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.