vendredi 1 juin 2018

How to instantiate a list of System.Types from a literal?

I have a few types:

public ClassA
{
}

public ClassB
{
}

public ClassC
{
}

Now I would like to store some of them in a list?

Some of the failed approaches I've tried:

List<System.Type> allowedTypes = new List<System.Type>{ ClassA, ClassC };

List<System.Type> allowedTypes = new List<System.Type>{ System.Type.GetType(ClassA), Systme.Type.GetType(ClassC) };

List<System.Type> allowedTypes = new List<System.Type>{ ClassA.GetType(), ClassC.GetType() };

The working approaches I am aware of seem pretty cumbersome:

List<System.Type> allowedTypes = new List<System.Type>{ new ClassA().GetType(), new ClassB().GetType() };

This approach is cumbersome because it requires ClassA and ClassC to be specifically prepared for such a use.

List<System.Type> allowedTypes = new List<System.Type>{ System.Type.GetType("ClassA"), System.Type.GetType("ClassC") };

If there's no way to get rid of these magic strings then well, I guess I should embrace them...





Aucun commentaire:

Enregistrer un commentaire