且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何确保流利的API中的方法顺序?

更新时间:2021-10-29 04:48:03

以下是按特定顺序强制执行方法链的示例代码.我使用了此处中的示例,并修复了原始代码中的一个小问题. 此处是dotnet提琴手中正在运行的代码

Here is the sample code that enforces method chain in specific order. I've used the example from here and fixed a minor issue in the original code. Here is the running code in dotnet fiddler

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; }


    public IAge WithName(string name)
    {
        Name = name;
        return this;
    }

    public IPersist WithAge(int age)
    {
        Age = age;
        return this;
    }

    public void Save()
    {
        // save changes here
    }
}