加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么要限制泛型键入界面?

发布时间:2020-12-15 22:25:42 所属栏目:百科 来源:网络整理
导读:在C#中对泛型的接口类型进行约束会有什么意义?例如, public interface IHandlerin T where T : IProcessor{ void Handle(T command);} 简单地将IProcessor作为通用继承而没有任何约束不是更好吗?这样做有什么好处? 例如, public class Test: IProcessorT{
在C#中对泛型的接口类型进行约束会有什么意义?例如,

public interface IHandler<in T> where T : IProcessor
{
    void Handle(T command);
}

简单地将IProcessor作为通用继承而没有任何约束不是更好吗?这样做有什么好处?

例如,

public class Test: IProcessor<T>{void Handle(T command);}

解决方法

如果接口为空,则为 marker interface.

它可以用于对类外的类进行限制.与下面的示例一致,您可以限制装饰器只能装饰IProcessor的处理程序.

一个非常正当的理由是在申请装饰时:

假设命令参数接口有几个属性:

public interface IProcessor
{
    int Id { get; }
    DateTime Date { get; }
}

我们可以在IProcessor命令的所有处理程序上定义一个装饰器,它知道所有命令参数都有Id和Date:

public sealed class HandlerLogger<in T> where T : IProcessor
{
    private readonly ILogger logger;
    private readonly IHandlerLogger<T> decorated;

    public HandlerLogger(
        ILogger logger,IHandlerLogger<T> decorated)
    {
        this.logger = logger;
        this.decorated = decorated;
    }

    public void Handle(T command)
    {
        this.logger.Log(command.Id,command.Date,typeof(T).Name);
        this.decorated.Handle(command);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读