vendredi 25 novembre 2016

C# - Cleaner way to instantiate different derived class based on collection size?

Ive been trying to make a flexible method where it will fill a single collection with different derived types. I want this method to also expand its capability based on a collection of types. Problem is, for it to look super, i need to replace an explicit cast class name with a type. I read this question here that it is not possible to cast using a class name not known at compile time.

My question to you is how would you go about refactoring this code to make it less repeating and be flexible based on collection size?

Speeches = new List <SentenceFactory>();

for (int i = 0; i < POSSIBLE_OUTPUTS.AllOptions.Count; i++)
{
    for (int k = 0; k < TOTAL_SPEECHES; k++)
    {     
        if (POSSIBLE_OUTPUTS.AllOptions[i] == POSSIBLE_OUTPUTS.HawkingType)
        {
            Speeches.Add (Activator.CreateInstance (POSSIBLE_OUTPUTS.AllOptions[i]) as MarekVoice);                                       
        }

        else if (POSSIBLE_OUTPUTS.AllOptions[i] == POSSIBLE_OUTPUTS.HawkingType)
        {
            Speeches.Add (Activator.CreateInstance (POSSIBLE_OUTPUTS.AllOptions[i]) as HawkingVoice);                                       
        }

        else if (POSSIBLE_OUTPUTS.AllOptions[i] == POSSIBLE_OUTPUTS.HawkingType)
        {
            Speeches.Add (Activator.CreateInstance (POSSIBLE_OUTPUTS.AllOptions[i]) as GLADOSVoice);                                       
        }    
    }                
}





Aucun commentaire:

Enregistrer un commentaire