Enum “Inheritance”

后端 未结 15 1643
野性不改
野性不改 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:02

    This is what I did. What I've done differently is use the same name and the new keyword on the "consuming" enum. Since the name of the enum is the same, you can just mindlessly use it and it will be right. Plus you get intellisense. You just have to manually take care when setting it up that the values are copied over from the base and keep them sync'ed. You can help that along with code comments. This is another reason why in the database when storing enum values I always store the string, not the value. Because if you are using automatically assigned increasing integer values those can change over time.

    // Base Class for balls 
    public class BaseBall
    {
        // keep synced with subclasses!
        public enum Sizes
        {
            Small,
            Medium,
            Large
        }
    }
    
    public class VolleyBall : BaseBall
    {
        // keep synced with base class!
        public new enum Sizes
        {
            Small = BaseBall.Sizes.Small,
            Medium = BaseBall.Sizes.Medium,
            Large = BaseBall.Sizes.Large,
            SmallMedium,
            MediumLarge,
            Ginormous
        }
    }
    

提交回复
热议问题