如何确保流利的API中的方法顺序? [英] How to ensure the sequence of methods in fluent API?

查看:63
本文介绍了如何确保流利的API中的方法顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我正在作为框架的一部分而构建的某些类创建流畅的界面.我已经创建了方法,并且能够成功地链接方法.现在,我要确保可以处理不正确的方法调用序列.

I want to create fluent interface for some of my classes that I am building as part of a framework. I have created the methods and I am able to successfully chain methods. Now I want to ensure that I can handle the improper sequence of method calls.

我正在做的事情类似于CreateWorkflow-> OpenConfiguration-> ChangeUserName 在上述情况下,如果首先调用ChangeUserName是没有意义的,因为它依赖于OpenConfiguration.

The thing I am doing is something like CreateWorkflow -> OpenConfiguration -> ChangeUserName In the above scenario it wouldn't make sense if ChangeUserName was called first because it is dependent on OpenConfiguration.

对于在这种情况下创建Fluent方法链是否正确以及如何使序列起作用,我感到困惑.对我来说,这种情况似乎非常适合创建流畅的API.

I am confused whether I am correct in creating a Fluent chain of methods for this scenario or not and how to make the sequence work. To me this scenario seems to be very suitable for creating a fluent API.

推荐答案

以下是按特定顺序强制执行方法链的示例代码.我使用了此处中的示例,并修复了原始代码中的一个小问题. 此处是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
    }
}

这篇关于如何确保流利的API中的方法顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆