Why restrict the interface with typical typing?

What is the point of creating a constraint for an interface type on a common in C #? For example,

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

Wouldn't it be better to just inherit the IProcessor as a shared one without any restrictions? What is the advantage of this?

For example,

public class Test: IProcessor<T>{void Handle(T command);}
+4
source share
2 answers

If the interface is empty, then this is the marker interface .

It can be used to apply class constraints, outside the class. According to the example below, you can restrict the decorator to only decorate handlers with IProcessor.


A very important reason is to use a decorator:

, :

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);
    }
}
+1

, .
, API - , , , , . - .

adhoc, , / .

public class UnitOfWorkManager<T>
{
    private readonly IDataRepository _dataRepository;
    private List<T> _unitOfWorkItems;

    public UnitOfWorkManager(IDataRepository dataRepository)
    {
        _dataRepository = dataRepository;
    }

    public void AddUnitOfWork(IUnitOfWork<T> unitOfWork)
    {
        this._unitOfWorkItems.Add(unitOfWork);
    }

    public void Execute()
    {
        WorkerItem previous = null;
        foreach (var item in _unitOfWorkItems)
        {
            var repoItem = _dataRepository.Get(item.Id);
            var input = new WorkerItem(item.Id, repoItem.Name, previous);
            previous = input;
        }
    }
}

public interface IUnitOfWork<T> 
    where T: WorkerItem, new()
{
    string Id { get; }
    void Execute(T input);
}

public class WorkerItem
{
    public WorkerItem(string id, string name, WorkerItem previous)
    {
        this.Name = name;
        this.Id = id;
        this.Previous = previous;
    }
    public string Id { get; private set; }
    public string Name { get; private set; }
    public WorkerItem Previous { get; private set; }
}

, .

0

Source: https://habr.com/ru/post/1625886/


All Articles