jeudi 28 juillet 2016

Force a class to implement a specific constructor [duplicate]

This question already has an answer here:

Let's say I have the following class:

public class SomeClass<TSource>
{

     private Model _model;

     // ...

     public void SomeMethod()
     {
         // ...
         TSource instance = Activator.CreateInstance(typeof(TSource), _model);
         // ...
     }
}

And then I have this class:

public class OtherClass
{
     public OtherClass(Model model)
     {
         // ...
     }
}

If I do the following, everything's fine:

SomeClass<OtherClass> someClass = // ....
someClass.SomeMethod();

But what if OtherClass has a parameterless constructor, or any constructor different than the stated?

Everything will compile just fine, but when creating the instance a runtime exception will be raised.

Is there a way to enforce the use of a certain constructor on every class that will be used as a generic argument to SomeClass<> ? (Like a generic constraint)





Aucun commentaire:

Enregistrer un commentaire