Best practice for a collection of generic classes

Consider the following code:

abstract class SomeClassX<T>
{
  // blah
}

class SomeClassY: SomeClassX<int>
{
  // blah
}

class SomeClassZ: SomeClassX<long>
{
  // blah
}

I need a collection SomeClassX <T>, however this is not possible since SomeClassX <int>! = SomeClassX <long> and List <SomeClassX → are not allowed.

So my solution is to have SomeClassX <T> implement the interface and define my collection as where ISomeClassX is the interface:

class CollectionOfSomeClassX: List<ISomeClassX>
{
  // blah
}

Is this the best way to do this, or is there a better way?

+3
source share
2 answers

, , SomeClassX . , . , , , .

+1

, , ISomeClass . , . :

public interface IEntry
{
    // ...
    object Value { get; set; }
}

Entry<Single> , Entry<T> :

public class Entry<T> : IEntry
{
    T Value { get; set; }
    object IEntry.Value { get { return Value; } set { return Value; } }
}

IDictionary<string,IEntry> , IEntry Entry<T> Value IEntry .

// assume entries is IDictionary<string,IEntry>...
var entry = entries["pizza-weight"];
var weight = (float)entry.Value;

, , , SomeClass<int>!= SomeClass<long> IList<SomeClass<int>>!= IList<SomeClass<long>>.

+1

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


All Articles