Common set of limited types

I have a class that needs the following definition:

public class Table<T> : ObservableCollection<T> where T : IRowDef, new()

I want to create his collection and types of cards with instances. Therefore, I try:

public sealed class TableCollection : IEnumerable<Table<IRowDef>>
{
   private Dictionary<Type, Table<IRowDef>> _tableDictionary;

   public Table<IRowDef> GetTable<T>() where T : IRowDef, new()
   {
        Table<IRowDef> table = null;

        if (_tableDictionary.ContainsKey(typeof(T)))
        {
            table = _tableDictionary[typeof(T)];
        }
        else
        {
            table = new Table<IRowDef>();
            _tableDictionary.Add(typeof(T), table);
        }

        return table;
   }

   ...
}

But I can’t make it work. The following lines and several others give the same error:

private Dictionary<Type, Table<IRowDef>> _tableDictionary;

The error translated reports that IRowDef must be non-abstract and have a constructor without parameters. I know that this comes from a restriction like "new ()" to define the table class, but it is necessary for the code inside this class. I knew that I could solve this using a specific type of class that would contain less constructor with a parameter, for example:

private Dictionary<Type, Table<ClientTable>> _tableDictionary;

But different types of tables must be supported and are the reason that they all implement IRowDef.

Does anyone know how I can solve this?

+4
3

, , Table<X> Table<Y>, WhateverCollection<Table<X>> WhateverCollection<Table<Y>>, X - Y .

? ,

List<IAnimal> animals = new List<Elefant>();
animals.Add(giraffe); // Ooops!

!

// DOES NOT WORK!  
T<Base> b = new T<Derived>(); // T<Derived> is not assignment compatible to T<Base>!!!

Base b = new Derived(); // OK

, : :

public abstract class Table
{}

public class Table<T> : Table
     where T : IRowDef, new()
{
     private readonly ObservableCollection<T> _rows = new ...;
}

private Dictionary<Type, Table> _tableDictionary;

, , ( )! ITable Table Table<T> ITable, Dictionary<Type, ITable>.

+1

new() Activator.CreateInstance<T>() . . # new T() Activator.CreateInstance .

0

Olivier Jacof-Descombe proposed one of the possible approaches. Another (applicable only if you can change the class Table):

public interface ITable
{
    //Some needed methods, f,e,
    IRowDef GetSth();
}

then

public class Table<T> : ..., ITable where T : IRowDef, new()
{
    IRowDef ITable.GetSth()
    { 
         return (IRowDef)this.GetSthImplInsideTable(); // cast is optional
    }

    public T GetSthImplInsideTable() { /* impl */ }
}

You can use it like:

private Dictionary<T, ITable> _tablesDict;
0
source

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


All Articles