流畅的接口实现
为了使我的代码更有条理,我决定使用流畅的接口; 然而,通过阅读可用的教程,我找到了很多方法来实现这种流畅性,其中我找到了一个主题,他说创建Fluent Interface
我们应该使用Interfaces
,但他没有提供任何好的细节来实现它。
这是我如何实现Fluent API
码
public class Person { public string Name { get; private set; } public int Age { get; private set; } public static Person CreateNew() { return new Person(); } public Person WithName(string name) { Name = name; return this; } public Person WithAge(int age) { Age = age; return this; } }
使用守则
Person person = Person.CreateNew().WithName("John").WithAge(21);
但是,我如何让Interfaces以更有效的方式创建Fluent API?
如果要控制调用的顺序,使用interface
实现流畅的API是很好的。 我们假设在您设置名称的示例中,您还希望允许设置年龄。 并且我们假设您需要保存此更改,但仅限于设置年龄之后。 要实现这一点,您需要使用接口并将它们用作返回类型。 看例子:
public interface IName { IAge WithName(string name); } public interface IAge { IPersist WithAge(int age); } public interface IPersist { void Save(); } public class Person : IName, IAge, IPersist { public string Name { get; private set; } public int Age { get; private set; } private Person(){} public static IName Create() { return new Person(); } public IAge WithName(string name) { Name = name; return this; } public IPersist WithAge(int age) { Age = age; return this; } public void Save() { // save changes here } }
但如果你的具体情况好/需要,仍然遵循这种方法。
- 使用委托条件二进制搜索C#列表
- 在iTextSharp中确定属性,例如PDF是单面还是双面
- 在Excel中最后一行下方动态显示Datagridview列总和的最佳方法?
- 如何在Windows应用程序C#上播放YouTubevideo
- 如何在C#.NET(win7手机)中使用’DataContractJsonSerializer’读入’嵌套’Json文件?
- 使用C#中的RSA私钥文件创建RSACryptoServiceProvider对象
- 使用C#以编程方式设置时间
- Azure Web角色上的WaitHandleCannotBeOpenedException以Task.Wait()开头
- 使用mongo C#驱动程序在嵌入式文档中维护Id属性名称