Tips for writing fluent interfaces in C# 3

前端 未结 8 1723
借酒劲吻你
借酒劲吻你 2020-12-07 11:39

I\'m after some good tips for fluent interfaces in C#. I\'m just learning about it myself but keen to hear what others think outside of the articles I am reading. In particu

8条回答
  •  旧巷少年郎
    2020-12-07 12:04

    I too am just jumping on learning how to write a fluent interface for a small app at work. I've asked around and researched a little and found that a good approach for writing a fluent interface is using the "Builder pattern", read more about it here.

    In essence, this is how I started mine:

    public class Coffee
    {
        private bool _cream;
        private int _ounces;
    
        public Coffee Make { get new Coffee(); }
    
        public Coffee WithCream()
        {
            _cream = true;
            return this;
        }
    
        public Coffee WithOuncesToServe(int ounces)
        {
            _ounces = ounces;
            return this;
        }
    }
    

    Here's a cross post to a similar question I have for implementing a closure in a fluent interface.

提交回复
热议问题