mercredi 3 janvier 2018

How nice to cast a class to the interface that it implements, but not at the moment of its creation

There is a code in which there is this implementation:

using System;
using System.Collections.Generic;

namespace ConsoleApp{

    public interface IModel { } 

    public class Model : IModel { }

    public interface IDataBuilder<T> where T : IModel
    {
        T Build();
    }

    public interface IActionBuilder<T> where T : IModel
    {
        object BuildAction(T model);
    }

    public interface ISet<T> where T : IModel
    {
        IDataBuilder<T> DataBuilder { get; } 
        IActionBuilder<T> ActionBuilder { get;}
    }

    public class Builder
    {
        private List<ISet<IModel>> _dataBuilders;
        public void AddSet(ISet<IModel> _dataBuilder)
        {
            _dataBuilders.Add(_dataBuilder);
        }
    }

    public class MySet : ISet<Model>
    {
        public IDataBuilder<Model> DataBuilder => throw;    
        public IActionBuilder<Model> ActionBuilder  => throw;
    } 

    public class Program 
    {
        static void Main(string[] args)
        {
            var builder = new Builder(); 
            builder.AddSet( new MySet() );
        }      
    }   
} 

And in the line

builder.AddSet( new MySet() );

I get this error:

Program.cs(56, 29): [CS1503] Argument 1: cannot convert from 'ConsoleApp.MySet' to 'ConsoleApp.ISet<ConsoleApp.IModel>'

Naturally, I can just directly cast:

var builder = new Builder(); 
builder.AddSet( (ISet<IModel>)new MySet() );

But in my case this is not an option, I need it to work out architecturally without such a cast.

Playing with covariance and invariance has not helped unfortunately.

Aucun commentaire:

Enregistrer un commentaire