General solution for simple classes + factory

My little mind cannot come up with an elegant solution to this problem. Suppose I have a class like this:

    public class Foo<T>
    {
        public RecordType Type { get; set; }
        public T Value { get; set; }
    }

Where it RecordTypemight look something like this:

 public enum RecordType
    {
        EmptyRecord,
        BooleanRecord,
        IntegerRecord,
        StringRecord,
        ByteRecord
    }

The goal is to evenly process IEnumerable<Foo<T>>for iteration and / or enable RecordTypeand execute an action, while avoiding boxing of internal types, if at all possible. Also, it would be nice to use a factory to create these Foousing the factory method.

I was looking for a few quick implementations of generality in a base class or interface, and none of what I came up with answered this seemingly very simple problem elegantly.

: , - .Value, .

+3
1

IFoo:

public interface IFoo
{
    RecordType Type { get; set; }
}

Foo:

public class Foo<T> : IFoo
{
    public T Value { get; set; }
}

factory, Foo RecordType:

public static IFoo CreateFoo(RecordType type)
{
    switch (type)
    {
        case RecordType.Bool: return new Foo<bool>();
        // ...
    }
}

Foo , , . Type :

IFoo foo = CreateFoo(RecordType.Bool);

if (foo.Type == RecordType.Bool)
{
    Foo<bool> boolFoo = (Foo<bool>)foo;
    bool value = boolFoo.Value;
}

, Foo, :

void DoIt<T>(IEnumerable<Foo<T>> foos)
{
    foreach (Foo<T> foo in foos)
    {
        Qux(foo.Value);
    }
}

IFoo, Cast/OfType, :

IEnumerable<IFoo> foos = // ...
DoIt<bool>(foos.OfType<Foo<bool>>());

, , Foo <T> T IFoo, T . IFoo , Foo <T> T .

+2

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


All Articles