gpt4 book ai didi

c# - 无法在 C# 中将具体类型转换为其接口(interface)的泛型版本

转载 作者:太空狗 更新时间:2023-10-29 20:36:17 24 4
gpt4 key购买 nike

我有以下界面:

public interface INotificationHandler<T>
{
Task<T> Handle(string msg);
}

还有几个像这样愉快地实现它的类:

public class FooHandler : INotificationHandler<Foo>
{
public Task<Foo> Handle(string msg) { return Task.FromResult<Foo>(new Foo()); }
}

public class BarHandler : INotificationHandler<Bar>
{
public Task<Bar> Handle(string msg) { return Task.FromResult<Bar>(new Bar()); }
}

我想在一个集合中保留一组 INotificationHandler 实例,当我收到消息“foo”时,使用 FooHandler,“bar”获取 BarHandler,等等...

var notificationHandlers = new Dictionary<string, INotificationHandler<object>>();
notificationHandlers["foo"] = new FooHandler();
notificationHandlers["bar"] = new BarHandler();
...
public void MessageReceived(string type, string msg)
{
INotificationHandler<object> handler = notificationHandlers[type];
handler.Notify(msg).ContinueWith((result) => /* do stuff with a plain object */)
}

但是这无法编译,因为我的泛型没有公共(public)基类型,这是设计使然。任何对象都应该能够从 MessageReceived 中的 INotificationHandler 返回.

Cannot implicitly convert type FooHandler to INotificationHandler<object>. An explicit conversion exists (are you missing a cast?)

我如何使用 INotificationHandler<T>这样我就不需要关心其具体实现的泛型类型?

最佳答案

如果您需要类型安全,您可以使用以下层次结构。

public interface INotificationHandler
{
Task<object> Handle(string msg);
}

public abstract BaseHandler<T> : INotificationHandler
{
Task<object> INotificationHandler.Handle(string msg)
{
return Handle(msg);
}

public abstract Task<T> Handle(string msg);
}

public class FooHandler : BaseHandler<Foo>
{
public override Task<Foo> Handle(string msg) { return Task.FromResult<Foo>(new Foo()); }
}

public class BarHandler : BaseHandler<Bar>
{
public override Task<Bar> Handle(string msg) { return Task.FromResult<Bar>(new Bar()); }
}

var notificationHandlers = new Dictionary<string, INotificationHandler>();
notificationHandlers["foo"] = new FooHandler();
notificationHandlers["bar"] = new BarHandler();
...
public void MessageReceived(string type, string msg)
{
INotificationHandler handler = notificationHandlers[type];
handler.Notify(msg).ContinueWith((result) => /* do stuff with a plain object */)
}

关于c# - 无法在 C# 中将具体类型转换为其接口(interface)的泛型版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31858551/

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