Less defined generics in C #?

Is there a way to use a collection of a generic class without providing a base type? Explain:

Here is what I would like to have:

class TimeSerie<TValue> {
enter code here
}

List<TimeSerie<?>> blah;

Here is what I need to do so far:

class TimeSerie {}
class TypedTimeSerie<TValue> : TimeSerie {}

List<TimeSerie> blah;

So, in any way you can use a good first solution? (although I suppose this will cause problems when trying to quit, for example, for a loop ...)

+3
source share
5 answers

... - . . , , , -.

+8

, ICollection<T> List<T> (, , ICollection List<T>, ?

(, , ?)

+1

?

List<TimeSerie<Object>> blah;

, . .

+1

, "" # :

( , 2), .

public static class Mumble 
{
    public static HashSet<T> HashSet<T>(T prototype)
    {
        return new HashSet<T>();
    }

    public static List<T> List<T>(T prototype)
    {
        return new List<T>();
    } 
}

:

var set = MumbleSet(new { Foo="", Bar="", Baz=0 });
var list = MumbleList(new { Foo="", Bar="", Baz=0 });
set.Add(new { Foo="x", Bar="y", Baz=1 });
set.Add(new { Foo="a", Bar="b", Baz=1 });
list.Add(new { Foo="a", Bar="b", Baz=1 });
var intersection = list.Intersect(set);
var concat = list.Concat(set); 

, , - . , linq , .

:

class TimeSerie<TValue> 
{   
    // or some other constructor equivalent 
    public TimeSerie(TValue value) { /* assign the value */ }
}

static class TimeSerieMumble
{
    public static TimeSerie<TValue> New<TValue>(TValue value)
    {
        return new TimeSerie<TValue>(value);
    }
}

:

var tsList = Mumble.List(TimeSerieMumble.New(new { Name="", Value=0 }));
foreach (var x in from c select new { c.Name, c.Value })
{
    tsList.Add(TimeSerieMumble.New(new { x.Name, x.Value }));
}

, "" public api # 3.5, , , , . , , , . , . , "/" .

+1

, # . , , , , :

interface ITimeSeriesUser<X> {
    X Use<T>(TimeSeries<T> series);
}

interface ITimeSeriesUser {
    void Use<T>(TimeSeries<T> series);
}

interface ITimeSeries {
    X Apply<X>(ITimeSeriesUser<X> user);
    void Apply(ITimeSeriesUser user);
}

class TimeSeries<T> : ITimeSeries {
    X Apply<X>(ITimeSeriesUser<X> user) { return user.Use(this); }
    void Apply(ITimeSeriesUser user) { return user.Use(this); }

    /* Your existing code goes here */
}

Now you can create an instance List<ITimeSeries>that contains TimeSeries<T>  whatever type arguments they are, and you can use ITimeSeriesUser implementations to manipulate them. Obviously, this requires quite a few templates, but if you need the right way to express the concept TimeSeries<?>, then this might be your best bet.

0
source

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


All Articles