gpt4 book ai didi

c# - 通用处理程序的集合——这可能吗?

转载 作者:行者123 更新时间:2023-11-30 12:56:21 24 4
gpt4 key购买 nike

使用泛型是否可以将泛型集合定义为基类型并分配子类型的实例?我在下面有一个简单的代码示例,突出显示了我的想法和导致编译器错误的行。我知道我可以创建一个 IEventHandler 标记接口(interface)并使我的通用事件处理程序从中继承。这将使我可以将泛型类型存储在 IList 的集合中,但这似乎不太理想。有没有类似于我下面的代码的方法?

using System;
using System.Collections.Generic;

namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
IEventHandler<SomeEvent1> handler1 = new SomeEvent1Handler();
IEventHandler<SomeEvent2> handler2 = new SomeEvent2Handler();


IList<IEventHandler<IEvent>> handlers = new List<IEventHandler<IEvent>>();
// COMPILE ERROR - is this possible?
handlers.Add(new SomeEvent1Handler());
}

public interface IEvent {

}

public interface IEventHandler<in TEvent> where TEvent : IEvent
{
void Handle(TEvent someEvent);
}

public class SomeEvent1 : IEvent {
}
public class SomeEvent2 : IEvent {
}

public class SomeEvent1Handler : IEventHandler<SomeEvent1>
{
public void Handle(SomeEvent1 someEvent)
{
throw new NotImplementedException();
}
}

public class SomeEvent2Handler : IEventHandler<SomeEvent2>
{
public void Handle(SomeEvent2 someEvent)
{
throw new NotImplementedException();
}
}
}

}

最佳答案

Using generics is it possible to have a generic collection defined as a base type and assign instances of a sub type?

是的,但只有当你的界面是IEventHandler<out TEvent>时才能完成, 你不能用 in 来做.

如果你的代码确实有效,如果代码是,你会期望发生什么

    public static void Main(string[] args)
{
IList<IEventHandler<IEvent>> handlers = new List<IEventHandler<IEvent>>();
handlers.Add(new SomeEvent1Handler()); //Magicly works
IEventHandler<IEvent> handler = handlers[0];
handler.Handle(new SomeEvent2());
}

handler声明它允许任何 IEvent传递给它的 Handle功能。这会导致 SomeEvent1Handler将通过 SomeEvent2反对其 public void Handle(SomeEvent1 someEvent)方法。

我的解决方法是让处理程序只接受 IEvent ,在函数中他们检查它是否是他们不关心的事件类型他们可以从函数返回而不做任何事情。

using System;
using System.Collections.Generic;

namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
IEventHandler<SomeEvent1> handler1 = new SomeEvent1Handler();
IEventHandler<SomeEvent2> handler2 = new SomeEvent2Handler();


IList<IEventHandler> handlers = new List<IEventHandler>();

handlers.Add(new SomeEvent1Handler());
}

public interface IEvent {

}

public interface IEventHandler
{
void Handle(IEvent someEvent);
}

public class SomeEvent1 : IEvent {
}
public class SomeEvent2 : IEvent {
}

public class SomeEvent1Handler : IEventHandler
{
public void Handle(IEvent someEvent)
{
var event = someEvent as SomeEvent1;
if(event == null)
return;

//Do stuff here.
}
}

public class SomeEvent2Handler : IEventHandler
{
public void Handle(IEvent someEvent)
{
var event = someEvent as SomeEvent2;
if(event == null)
return;

//Do stuff here.
}
}
}

}

关于c# - 通用处理程序的集合——这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41702803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com