流式接口(fluent interface)
流式接口(fluent interface)是软件工程中面向对象API的一种实现方式,以提供更为可读的源代码。最早由Eric Evans与Martin Fowler于2005年提出。
通常采取方法瀑布调用 (具体说是方法链式调用)来转发一系列对象方法调用的上下文 [1]。这个上下文(context)通常是指:
- 通过被调方法的返回值定义
- 自引用,新的上下文等于老的上下文。
- 只有一条规则:该方法必须返回非void值。
流式接口可用于一系列方法,他们运行在同一对象上。linq大量使用了流式接口
// Defines the data context class Context { public string FirstName { get; set; } public string LastName { get; set; } public string Sex { get; set; } public string Address { get; set; } } class Customer { private Context _context = new Context(); // Initializes the context // set the value for properties public Customer FirstName(string firstName) { _context.FirstName = firstName; return this; } public Customer LastName(string lastName) { _context.LastName = lastName; return this; } public Customer Sex(string sex) { _context.Sex = sex; return this; } public Customer Address(string address) { _context.Address = address; return this; } // Prints the data to console public void Print() { Console.WriteLine("First name: {0} \nLast name: {1} \nSex: {2} \nAddress: {3}", _context.FirstName, _context.LastName, _context.Sex, _context.Address); } } class Program { static void Main(string[] args) { // Object creation Customer c1 = new Customer(); // Using the method chaining to assign & print data with a single line c1.FirstName("vinod").LastName("srivastav").Sex("male").Address("bangalore").Print(); } }
编程是个人爱好
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2021-10-01 模式匹配
2021-10-01 解构函数(Deconstruct)
2021-10-01 C#中 Var关键字