我以前上过这种课,我不记得具体是怎么做的了。
假设你有这个类:
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/