Enum “Inheritance”

后端 未结 15 1634
野性不改
野性不改 2020-11-22 07:21

I have an enum in a low level namespace. I\'d like to provide a class or enum in a mid level namespace that \"inherits\" the low level enum.

namespace low
{
         


        
15条回答
  •  春和景丽
    2020-11-22 08:20

    I know this answer is kind of late but this is what I ended up doing:

    public class BaseAnimal : IEquatable
    {
        public string Name { private set; get; }
        public int Value { private set; get; }
    
        public BaseAnimal(int value, String name)
        {
            this.Name = name;
            this.Value = value;
        }
    
        public override String ToString()
        {
            return Name;
        }
    
        public bool Equals(BaseAnimal other)
        {
            return other.Name == this.Name && other.Value == this.Value;
        }
    }
    
    public class AnimalType : BaseAnimal
    {
        public static readonly BaseAnimal Invertebrate = new BaseAnimal(1, "Invertebrate");
    
        public static readonly BaseAnimal Amphibians = new BaseAnimal(2, "Amphibians");
    
        // etc        
    }
    
    public class DogType : AnimalType
    {
        public static readonly BaseAnimal Golden_Retriever = new BaseAnimal(3, "Golden_Retriever");
    
        public static readonly BaseAnimal Great_Dane = new BaseAnimal(4, "Great_Dane");
    
        // etc        
    }
    

    Then I am able to do things like:

    public void SomeMethod()
    {
        var a = AnimalType.Amphibians;
        var b = AnimalType.Amphibians;
    
        if (a == b)
        {
            // should be equal
        }
    
        // call method as
        Foo(a);
    
        // using ifs
        if (a == AnimalType.Amphibians)
        {
        }
        else if (a == AnimalType.Invertebrate)
        {
        }
        else if (a == DogType.Golden_Retriever)
        {
        }
        // etc          
    }
    
    public void Foo(BaseAnimal typeOfAnimal)
    {
    }
    

提交回复
热议问题