类方法构建

时间:2018-02-03 14:09:51

标签: c#

我过去做过这种课,但我不记得究竟是怎么做的。

假设你有这门课程:

public class TestMethod
{
    private string a, b, c, d, e;

    public void SetA(string text) => a = text;
    public void SetB(string text) => b = text;
    public void SetC(string text) => c = text;
    public void SetD(string text) => d = text;
    public void SetE(string text) => e = text;

    public void Print()
    {
        Console.WriteLine(string.Format("A: {0}\nB: {1}\nC: {2}\nD: {3}\nE: {4}\n", a,b,c,d,e));
    }
}

你想这样称呼它:

TestMethod method = new TestMethod();
method.SetA("").SetB("").Print();

我需要将什么添加到我的课程中?这是什么?

1 个答案:

答案 0 :(得分:6)

这称为呼叫链。您必须添加return this声明。

public class TestMethod
{
    private string a, b, c, d, e;

    public TestMethod SetA(string text) { a = text; return this; }
    public TestMethod SetB(string text) { b = text; return this; }
    public TestMethod SetC(string text) { c = text; return this; }
    public TestMethod SetD(string text) { d = text; return this; }
    public TestMethod SetE(string text) { e = text; return this; }

    public void Print()
    {
        Console.WriteLine(string.Format("A: {0}\nB: {1}\nC: {2}\nD: {3}\nE: {4}\n", a,b,c,d,e));
    }
}