samedi 28 mai 2016

Create an instance of an unknown type

am pretty sure there is a few different ways of doing this, as i got very close to it without success with stuff like Activator.CreateInstance, but i wanted to see your opinion on my specific case.

Is there a way to avoid this kind of switches?

Resource r = null; <-- Resource is the base class of block,rock,plant types.

switch (type) //type is a byte you get from somewhere on runtime
{
    // Then you instantiate that class type depending on that "type byte", 
    // simply by comparing it to an enum lets say

    case ResourceType.Block:
        r = new Block();
        break;
    case ResourceType.Rock:
        r = new Rock();
        break;
    case ResourceType.Plant:
        r = new Plant();
        break;
}

//Then you apply some data to that newly created 'resource"
r.id = id;

//Then you save that 'resource' into a dictionary of resources.
ResourceDatabase.Add(r.id, r);





Aucun commentaire:

Enregistrer un commentaire