首页 新闻 会员 周边

C# 泛型约束问题

0
悬赏园豆:100 [已解决问题] 解决于 2023-02-21 14:23

下面的扩展方法想约束泛型 TEventHandler 的类型

public static void SubscribeByEventHandler<TEventHandler>(this IEndpointRouteBuilder builder)
    where TEventHandler : IIntegrationEventHandler<>
{ }

注:上面的 IIntegrationEventHandler<> 会引发编译错误 "Unexpected use of an unbound generic name"。

期望约束后支持如下的类型

public class TestIntegrationEventHandler : IntegrationEventHandler<TestIntegrationEvent>
{ }

IIntegrationEventHandler 接口对应的定义

public interface IIntegrationEventHandler<TEvent> : INotificationHandler<TEvent>
    where TEvent : IntegrationEvent
{ }

IntegrationEvent 对应的定义

public record IntegrationEvent(Guid Id, DateTimeOffset CreatedTime) : INotification
{ }

INotificationHandler 对应的定义

public interface INotificationHandler<in TNotification>
    where TNotification : INotification
{ }
问题补充:

找到了一个有所欠缺的实现方法,需要额外增加一个泛型类型

public static void SubscribeByEventHandler<TEventHandler, TEvent>(this IEndpointRouteBuilder builder)
    where TEventHandler : IIntegrationEventHandler<TEvent>
    where TEvent : IntegrationEvent
{ }

调用代码

app.SubscribeByEventHandler<TestIntegrationEventHandler, TestIntegrationEvent>();
dudu的主页 dudu | 高人七级 | 园豆:31003
提问于:2023-02-19 13:11
< >
分享
最佳答案
0

找到了一个基本可以接受的解决方法,引入一个专用于约束的非泛型版 IIntegrationEventHandler 接口

public interface IIntegrationEventHandler
{ }

泛型版的 IIntegrationEventHandler<TEvent> 继承它

public interface IIntegrationEventHandler<TEvent> : INotificationHandler<TEvent>, IIntegrationEventHandler
    where TEvent : IntegrationEvent
{ }

非泛型版的 IIntegrationEventHandler 专门用来进行约束(constraint)

public static void SubscribeByEventHandler<TEventHandler>(this IEndpointRouteBuilder builder)
    where TEventHandler : IIntegrationEventHandler
{ }

调用代码

app.SubscribeByEventHandler<TestIntegrationEventHandler>();
dudu | 高人七级 |园豆:31003 | 2023-02-19 14:37
其他回答(1)
0

都就是你找到的方法干的,包括微软也是这么写的~~

 

 ,当需要或者某个值时,甚至不惜代价 多一个看起来“一模一样”的 接口实现。补充一句——挺喜欢现在c#接口还可以写实现的。

收获园豆:100
花飘水流兮 | 园豆:13560 (专家六级) | 2023-02-20 15:17

那可以结帖了

支持(0) 反对(0) dudu | 园豆:31003 (高人七级) | 2023-02-21 14:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册