mardi 3 juillet 2018

Instantiating proper generic class by type parameter in C#

I have this code to perform operations under objects of Base class:

class Program
{
    static void Main(string[] args)
    {
        var list = new List<Base>() { new A(), new B() };
        var v = new Visitor();
        list.ForEach(e => e.Accept(v));
    }
}

public abstract class Base
{
    public abstract void Accept(Visitor visitor);
}

public class A : Base
{
    public override void Accept(Visitor visitor) => visitor.Visit(this);
}

public class B : Base
{
    public override void Accept(Visitor visitor) => visitor.Visit(this);
}

public class Visitor
{
    Writer writer = new Writer();
    public void Visit(A a) => writer.Write(a);
    public void Visit(B b) => writer.Write(b);
}

public class Writer
{
    public void Write(A a) => Console.WriteLine("A");
    public void Write(B b) => Console.WriteLine("B");
}

I want to divide Writer into separate classes, because there will be many other entities with complex hierarchy. It could be:

public interface Writer<T> where T : Base
{
    void Write(T t);
}

public class WriterA : Writer<A>
{
    public void Write(A t) => Console.WriteLine("A");
}

public class WriterB : Writer<B>
{
    public void Write(B t) => Console.WriteLine("B");
}

but I don't know how to instantiate proper classes by the given type parameter rather than calling them explicitly. Thanks.

Aucun commentaire:

Enregistrer un commentaire