What's the best C# pattern for implementing a hierarchy with an enum?

前端 未结 3 699
情深已故
情深已故 2021-02-14 17:10

I\'m implementing value types which represents a distance (or length). There\'s an enum that represents the different units of measure, eg:

public enum Distance         


        
3条回答
  •  有刺的猬
    2021-02-14 17:36

    Do you really need an enum here? Maybe, a simple value object will do?

    public class Distance
    {
        private readonly decimal millimeters;
    
        public decimal Meters
        { 
            get { return millimeters * 0.001m; } 
        }
    
        private Distance(decimal millimeters)
        {
            this.millimeters = millimeters;
        }
    
        public static Distance Yards(decimal yards)
        {
            return new Distance(yards * 914.4m);
        }
    }
    

    With extension methods you and properly defined operators can get very Ruby-like syntax:

    var theWholeNineYards = 9.Yards() + 34.Inches();
    

提交回复
热议问题