{C#}流畅方法.接口
2021-08-14 本文已影响0人
码农猫爸
背景
- 使用流畅方法后,能像lambda一样调用,是不是很神奇?
- 诀窍:返回类型=容器类型
示例
using static System.Console;
namespace FluentInterface
{
public interface IReporter
{
IReporter CreateHeader(); // 流畅方法=返回容器,下同
IReporter CreateBody();
IReporter CreateFooter();
}
public class Reporter : IReporter
{
public string Content { get; private set; } = "";
public Reporter() { }
public IReporter CreateHeader()
{
Content += "This is header.";
return this;
}
public IReporter CreateBody()
{
Content += "\nThis is body.";
return this;
}
public IReporter CreateFooter()
{
Content += "\nThis is footer.";
return this;
}
}
class Program
{
static void Main(string[] args)
{
var report = new Reporter();
report.CreateHeader()
.CreateBody()
.CreateFooter();
WriteLine(report.Content);
ReadKey();
}
}
}