dimanche 21 avril 2019

Naming properties at compile time on generic class

I am trying to write a generic class, pass some types to it and then access it via properties.

I have written this code:

class Factory<T1, T2> where T1 : Test, new()
                      where T2 : Test, new()
{
    public T1 FirstType { get; set; }
    public T2 SecondType { get; set; }

    public Factory() 
    {
        FirstType = new T1();
        SecondType = new T2();
    }
}

and I'm using it like this (OtherTest implements Test):

Factory<Test, OtherTest> factory = new Factory<Test, OtherTest>();
factory.FirstType.MyMethod();

Then I can use FirstType and SecondType properties, however if I change the order:

Factory<OtherTest, Test> factory2 = new Factory<OtherTest, Test>();

This would have different behaviour, since FirstType would be OtherTest. I would like to pass instances and be able to write code like this:

Factory<Test, OtherTest> factory = new Factory<Test, OtherTest>();
factory.Test.MyMethod();    //I want to generate properties named after class
factory.OtherTest.MyMethod();

Can I do this in compile time?





Aucun commentaire:

Enregistrer un commentaire