C# equivalent of Java's List<? extends MyFancyClass>

大憨熊 提交于 2021-02-11 08:57:56

问题


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.

// 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.

// 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. In Java you can use <? extends BaseClass> (self explanatory), is there something like Action<? : IEvent> or is this simply not possible?


回答1:


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
   }
}


来源:https://stackoverflow.com/questions/30036751/c-sharp-equivalent-of-javas-list-extends-myfancyclass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!