相当于Java的List的C#?扩展MyFancyClass& gt; [英] 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.
我目前正在编写一个具有事件API的应用程序,第三方可以将其插入其中,以下是我用来触发事件的代码.
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.
// 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
}
}
虽然上面的代码可以正常工作,但我发现第三方如何将其钩到非常丑陋的位置,并且想知道是否有可能使用 Action
类将其连接起来.
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.
// 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
}
}
我的目标是将Register方法更改为接受第三个参数 Action< IEvent>
,尽管我发现如果我引用一个方法,则它必须严格接受IEvent作为参数.在Java中,您可以使用< ;?扩展BaseClass>
(自我解释),是否有类似 Action<的东西?:IEvent>
还是根本不可能?
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. In Java you can use <? extends BaseClass>
(self explanatory), is there something like Action<? : IEvent>
or is this simply not possible?
推荐答案
此功能称为通用约束".您可以这样表达:
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
}
}
这篇关于相当于Java的List的C#?扩展MyFancyClass& gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!