如何根据枚举的名称动态创建对象?没有Switch

时间:2014-09-03 09:04:57

标签: c# enums

我有类似的东西

enum Animal
{
    Cat,
    Dog,
    Cow,
    Pigeon
}

和班级

public class Cow
{ }

public class Dog
{ }

public class Cow
{ }

public class Pigeon
{ }

我想要实现的是基于所选的enumu动态创建一个类对象。枚举和类名始终相同。枚举和类是几十个,所以我不想为每一对添加另一个案例。

如参见

public object GetAnimal(Animal animal)

GetAnimal(Animal.Cow);这样的

应该返回新的Cow类对象。

2 个答案:

答案 0 :(得分:7)

    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));
    }

答案 1 :(得分:2)

另一种方法是使用自定义属性和扩展方法,将方法的语法等效项添加到Enum。得到的答案要简单得多,因此可能会更好,但你可能会感兴趣。

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());
        }
    }
}