c# - 类方法构建

标签 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();

我需要在我的类(class)中添加什么,这叫做什么?

最佳答案

这称为调用链。您必须添加一个 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));
    }
}

关于c# - 类方法构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598271/

相关文章:

c# - 工作几个小时后 wcf 服务方法出错

c# - 在 Linq 中将两个 List<object> 合并为一个 List

c# - DebuggerStepThrough 属性 - 如何也跳过子方法

c# - MonoTouch-XCode的组织器中更好的控制台输出

c# - 使用导入函数时不必要加入 Entity Framework ?

c# - Ironpython:IEnumerator

c# - Parallel.Foreach 和 Task 冲突

c# - 尝试部署 Web 部件时出错

c# - 远程服务器返回错误 : "(405) Method Not Allowed"

c# - 字符串到 float 的转换 - 小数点分隔符