mercredi 28 février 2018

How can I skip a generic argument?

Can somebody help me with this issue?

I have a some class, which I can't change. Like this:

public class SomeBaseClass<T1, T2>
    where T2 : SomeBaseClass<T1, T2>
{ }

And I've made a child class:

public class SomeConcretClass : SomeBaseClass<int, SomeConcretClass>
{  }

Now, I want to create a factory for instantiate this classes. Like this:

public class SomeFactory
{
    public T2 CreateSome<T1, T2>()
        where T2 : SomeBaseClass<T1, T2>, new()
    {
        return new T2();
    }
}

As you can see, I need to use the T1 generic argument only for using it in the where construction, but it don't use in the factory method body. I want to implement Create method, like this:

public T2 CreateSome<T2>()
        where T2 : SomeBaseClass<, T2>, new()
    {
        return new T2();
    }

But I can't do this, because of C# restrictions. Is there some way to implement method, like I've described before with the where construction and without using the generic argument, or there is only one way - using Create method with only one generic argument and use reflection in method body to instantiate concrete class. If the second option is true, could somebody help me with correct using reflection in this case?





Aucun commentaire:

Enregistrer un commentaire