How to dynamically create an object based on an enum name? Without switch

I have something like this

enum Animal
{
    Cat,
    Dog,
    Cow,
    Pigeon
}

      

And class

public class Cow
{ }

public class Dog
{ }

public class Cow
{ }

public class Pigeon
{ }

      

What I want to achieve is dynamically creating a class object based on the selected enumu. The names of enumerations and classes are always the same. Enum and classes are dozens, so I don't want to add another case for each pair.

eq

public object GetAnimal(Animal animal)

used as GetAnimal(Animal.Cow);

, should return a new object of the Cow class.

+3


source to share


2 answers


    public object GetAnimal(Animal animal)
    {
        var ns = typeof(Animal).Namespace; //or your classes namespace if different
        var typeName = ns + "." + animal.ToString();

        return Activator.CreateInstance(Type.GetType(typeName));
    }

      



+6


source


An alternative is to use custom attributes and extension methods to add a syntactic equivalent to the Enum method. The agreed-upon answer is much simpler and therefore probably better, but you might find it interesting.



using System;
using System.Reflection;

namespace CustomAttributes
{
    [AttributeUsage(AttributeTargets.Field)]
    public class ConstructableEnumAttribute : Attribute
    {
        public Type Type { get; set; }

        public ConstructableEnumAttribute(Type type)
        {
            this.Type = type;
        }
    }

    public static class AnimalExtension
    {
        // This is your main mapping method.  It doesn't need to be an extension
        // method, so you could get the 'Construct(Animal.Cat)' syntax you requested,
        // but I like the ability to do:
        //     Animal myPet = Animal.Cat;
        //     object animal = myPet.Construct();
        public static object Construct(this Animal ofAnimal)
        {
            object animal = null;
            Type typeOfAnimal = GetType(ofAnimal);
            if ((null != typeOfAnimal) &&
                (!typeOfAnimal.IsAbstract))
            {
                animal = Activator.CreateInstance(typeOfAnimal);
            }
            return animal;
        }

        private static Type GetType(Animal animal)
        {
            ConstructableEnumAttribute attr = (ConstructableEnumAttribute)
                Attribute.GetCustomAttribute
                (ForValue(animal), typeof(ConstructableEnumAttribute));
            return attr.Type;
        }

        private static MemberInfo ForValue(Animal animal)
        {
            return typeof(Animal).GetField(Enum.GetName(typeof(Animal), animal));
        }
    }

    public enum Animal
    {
        [ConstructableEnum(typeof(Cat))]
        Cat,
        [ConstructableEnum(typeof(Dog))]
        Dog,
        [ConstructableEnum(typeof(Cow))]
        Cow,
        [ConstructableEnum(typeof(Pigeon))]
        Pigeon
    }

    public class Cat
    { }

    public class Dog
    { }

    public class Cow
    { }

    public class Pigeon
    { }

    public class Owner
    {
        Animal pet;
        Owner(Animal animal)
        {
            pet = animal;
        }

        public void ShowPet()
        {
            object theCreature = pet.Construct();
            Console.WriteLine("My pet is a " + theCreature.GetType().ToString());
        }
    }
}

      

+1


source







All Articles