【问题标题】:Fluent Interfaces Implementation流畅的接口实现
【发布时间】:2013-07-23 02:51:40
【问题描述】:

为了让我的代码更有条理,我决定使用流畅的接口;但是通过阅读可用的教程,我发现了很多实现这种流畅性的方法,其中我发现了一个主题,说要创建 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);

但是,我怎样才能让接口以更有效的方式创建 Fluent API?

【问题讨论】:

  • 这种方式有什么不好的地方?
  • @Sergey 我只是想知道如何使用那些家伙所说的接口来实现这样的 Fluent API...而且我不喜欢使用 With***,而是我想使用 Name、Age、等等......但由于属性名称,我不能在这种情况下
  • 有没有提到“那个家伙”?很高兴看到更大的问题,因为在这种情况下,您可以简单地执行 'new Person { Name="John", Age=21 }'
  • 我认为在这篇博客中,他为非常简单的问题提供了非常复杂的解决方案,对不起。

标签: c# fluent-interface


【解决方案1】:

如果你想控制调用的顺序,使用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
    }
}

但是,如果您的具体情况适合/需要,仍然遵循这种方法。

【讨论】:

  • 就是这样...简洁明了
猜你喜欢
  • 2021-10-28
  • 2014-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 2015-01-06
  • 2012-02-04
相关资源
最近更新 更多