mercredi 30 mars 2016

How to search a class within a namespace by the value of an attribute and return an object?

I need to make a factory of various objects. To be as abstract as possible. Able to create various objects, from a past condition by parameter, but without knewest concrete classes.

I want to do this by passing a value of an enum into a factory and it must be able, through reflection, to look for all classes within a namespace, which use the attribute whose value is the same as the last parameter.

I'm leaving the following code snippets to be used as reference.

An example of concrete class:

[Batatinha(SaborCode.Churrasco)]
internal class BatatinhaChurrasco : AbstractBatatinha
{
    public override string Sabor
    {
        get { return "Churrasco"; }
    }
}

An example of this factory:

internal class BatatinhaFactory
{
    internal AbstractBatatinha GetBatatinha(SaborCode sabor)
    {
        // Some logic ... possibly using reflection.
    }
}

An example of the desired call:

AbstractBatatinha batatinha = new BatatinhaFactory().GetBatatinha(SaborCode.Churrasco);
Console.WriteLine(batatinha.Sabor);
// ==> "Churrasco"





Aucun commentaire:

Enregistrer un commentaire