

C# 管道式编程 - hippieZhou
source link: https://www.cnblogs.com/hippieZhou/p/11174644.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

受 F# 中的管道运算符和 C# 中的 LINQ 语法,管道式编程为 C# 提供了更加灵活性的功能性编程。通过使用 扩展函数 可以将多个功能连接起来构建成一个管道。
前言#
在 C# 编程中,管道式编程(Pipeline Style programming)其实存在已久,最明显的就是我们经常使用的 LINQ。在进入 DotNetCore 世界后, 这种编程方式就更加明显,比如各种中间件的使用。通过使用这种编程方式,大大提高了代码的可维护性,优化了的业务的组合方式。
管道式编程具有如下优点:
- 创建一个流畅的编程范例,将语句转换为表达式并将它们链接在一起
- 用线性排序替换代码嵌套
- 消除变量声明 - 甚至不需要 var
- 提供某种形式的可变不变性和范围隔离
- 将结构代码编写成具有明确职责的小 lambda 表达式
- ......
初体验#
基础实现#
在该示例中,我们通过构建一个 double->int->string 的类型转换的管道来将一个目标数据最终转化为一个字符串。
- 首先,我们需要定义一个功能接口,用于约束每个功能函数的具体实现,示例代码如下所示:
public interface IPipelineStep<INPUT, OUTPUT>
{
OUTPUT Process(INPUT input);
}
- 然后,我们定义两个类型转换的功能类,继承并实现上述接口,示例代码如下所示:
public class DoubleToIntStep : IPipelineStep<double, int>
{
public int Process(double input)
{
return Convert.ToInt32(input);
}
}
public class IntToStringStep : IPipelineStep<int, string>
{
public string Process(int input)
{
return input.ToString();
}
}
- 接着,定义一个扩展函数,用于连接上述的各个功能函数,示例代码如下所示:
public static class PipelineStepExtensions
{
public static OUTPUT Step<INPUT, OUTPUT>(this INPUT input, IPipelineStep<INPUT, OUTPUT> step)
{
return step.Process(input);
}
}
- 最后,我们就可以构建一个完整的管道,用于我们的数据类型转换,示例代码如下所示:
class Program
{
static void Main(string[] args)
{
double input = 1024.1024;
// 构建并使用管道
string result = input.Step(new DoubleToIntStep())
.Step(new IntToStringStep());
Console.WriteLine(result);
}
}
此时,我们成功将一个 double
类型的数据转化为了 string
类型。通过介绍上述示例,我们可以简单将管道式编程概括为:定义功能接口 -> 实现功能函数 -> 组装功能函数 。
依赖注入#
上述代码在一般的情况下是可以正常运行的,但是如果希望以 依赖注入(DI) 的方式注入的话,我们就需要将我们的管道组装进行封装,方便作为一个统一的服务注入到系统中。
- 首先,我们需要定义一个抽线类,用于管道组装的抽象封装,示例代码如下所示:
public abstract class Pipeline<INPUT,OUTPUT>
{
public Func<INPUT, OUTPUT> PipelineSteps { get; protected set; }
public OUTPUT Process(INPUT input)
{
return PipelineSteps(input);
}
}
- 然后,我们就可以创建一个继承上述抽象类的具体管道组装类,示例代码如下所示:
public class TrivalPipeline : Pipeline<double, string>
{
public TrivalPipeline()
{
PipelineSteps = input => input.Step(new DoubleToIntSetp())
.Step(new IntToStringStep());
}
}
- 最后,我们可以将
TrivalPipeline
这个具体的管道注入到我们的系统中。同样的,我们也可以直接使用,示例代码如下所示:
class Program
{
static void Main(string[] args)
{
double input = 1024.1024;
// 需要安装 Microsoft.Extensions.DependencyInjection
var services = new ServiceCollection();
services.AddTransient<TrivalPipeline>();
var provider = services.BuildServiceProvider();
var trival = provider.GetService<TrivalPipeline>();
string result = trival.Process(input);
Console.WriteLine(result);
}
}
条件式组装#
上述两个示例代码展示的管道组装式不带任何条件限制的, 无论参数是否合法都是这样组装进管道,但是在实际的开发过程中,我们需要对一定的业务模块进行条件性组装,所以这个时候我们就需要完善一下我们的代码。
- 首先,我们需要修改上面的
Pipeline<INPUT,OUTPUT>
类,使其继承IPipelineStep<INPUT, OUTPUT>
接口,示例代码如下所示:
public abstract class Pipeline<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT>
{
public Func<INPUT, OUTPUT> PipelineSteps { get; protected set; }
public OUTPUT Process(INPUT input)
{
return PipelineSteps(input);
}
}
- 然后,我们定义一个带条件的管道装饰器类,示例代码如下所示:
public class OptionalStep<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT> where INPUT : OUTPUT
{
private readonly IPipelineStep<INPUT, OUTPUT> _step;
private readonly Func<INPUT, bool> _choice;
public OptionalStep(Func<INPUT,bool> choice,IPipelineStep<INPUT,OUTPUT> step)
{
_choice = choice;
_step = step;
}
public OUTPUT Process(INPUT input)
{
return _choice(input) ? _step.Process(input) : input;
}
}
- 接着,我们定义一个新的功能类和支持条件判断的管道包装类,示例代码如下所示:
public class ThisStepIsOptional : IPipelineStep<double, double>
{
public double Process(double input)
{
return input * 10;
}
}
public class PipelineWithOptionalStep : Pipeline<double, double>
{
public PipelineWithOptionalStep()
{
// 当输入参数大于 1024,执行 ThisStepIsOptional() 功能
PipelineSteps = input => input.Step(new OptionalStep<double, double>(i => i > 1024, new ThisStepIsOptional()));
}
}
- 最后,我们可以使用如下方式进行测试:
class Program
{
static void Main(string[] args)
{
PipelineWithOptionalStep step = new PipelineWithOptionalStep();
Console.WriteLine(step.Process(1024.1024)); // 输出 10241.024
Console.WriteLine(step.Process(520.520)); // 输出 520.520
}
}
事件监听#
有的时候,我们希望在我们管道中执行的每一步,在开始和结束时,上层模块都能获得相应的事件通知,这个时候,我们就需要需改一下我们的管道包装器,使其支持这个需求。
- 首先,我们需要实现一个支持事件监听的具体功能类,示例代码代码如下所示:
public class EventStep<INPUT, OUTPUT> : IPipelineStep<INPUT, OUTPUT>
{
public event Action<INPUT> OnInput;
public event Action<OUTPUT> OnOutput;
private readonly IPipelineStep<INPUT, OUTPUT> _innerStep;
public EventStep(IPipelineStep<INPUT,OUTPUT> innerStep)
{
_innerStep = innerStep;
}
public OUTPUT Process(INPUT input)
{
OnInput?.Invoke(input);
var output = _innerStep.Process(input);
OnOutput?.Invoke(output);
return output;
}
}
- 然后,我们需要定义一个能够传递事件参数的管道包装器类,示例代码如下所示:
public static class PipelineStepEventExtensions
{
public static OUTPUT Step<INPUT, OUTPUT>(this INPUT input, IPipelineStep<INPUT, OUTPUT> step, Action<INPUT> inputEvent = null, Action<OUTPUT> outputEvent = null)
{
if (inputEvent != null || outputEvent != null)
{
var eventDecorator = new EventStep<INPUT, OUTPUT>(step);
eventDecorator.OnInput += inputEvent;
eventDecorator.OnOutput += outputEvent;
return eventDecorator.Process(input);
}
return step.Process(input);
}
}
- 最后,上层调用就相对简单很多,示例代码如下所示:
public class DoubleStep : IPipelineStep<int, int>
{
public int Process(int input)
{
return input * input;
}
}
class Program
{
static void Main(string[] args)
{
var input = 10;
Console.WriteLine($"Input Value:{input}[{input.GetType()}]");
var pipeline = new EventStep<int, int>(new DoubleStep());
pipeline.OnInput += i => Console.WriteLine($"Input Value:{i}");
pipeline.OnOutput += o => Console.WriteLine($"Output Value:{o}");
var output = pipeline.Process(input);
Console.WriteLine($"Output Value: {output} [{output.GetType()}]");
Console.WriteLine("\r\n");
//补充:使用扩展方法进行调用
Console.WriteLine(10.Step(new DoubleStep(), i =>
{
Console.WriteLine($"Input Value:{i}");
},
o =>
{
Console.WriteLine($"Output Value:{o}");
}));
}
}
输出结果如下图所示:
可迭代执行#
可迭代执行是指当我们的管道中注册了多个功能模块时,不是一次性执行完所以的功能模块,而是每次只执行一个功能,后续功能会在下次执行该管道对应的代码块时接着执行,直到该管道中所有的功能模块执行完毕为止。该特性主要是通过 yield return
来实现。
- 首先,我们需要实现一个该特性的管道包装器类,示例代码如下所示:
public class LoopStep<INPUT, OUTPUT> : IPipelineStep<IEnumerable<INPUT>, IEnumerable<OUTPUT>>
{
private readonly IPipelineStep<INPUT, OUTPUT> _internalStep;
public LoopStep(IPipelineStep<INPUT,OUTPUT> internalStep)
{
_internalStep = internalStep;
}
public IEnumerable<OUTPUT> Process(IEnumerable<INPUT> input)
{
foreach (INPUT item in input)
{
yield return _internalStep.Process(item);
}
//等价于下述代码段
//return from INPUT item in input
// select _internalStep.Process(item);
}
}
- 然后,定义一个支持上述类型的功能组装的扩展方法,示例代码如下所示:
public static class PipelineStepLoopExtensions
{
public static IEnumerable<OUTPUT> Step<INPUT, OUTPUT>(this IEnumerable<INPUT> input, IPipelineStep<INPUT, OUTPUT> step)
{
LoopStep<INPUT, OUTPUT> loopDecorator = new LoopStep<INPUT, OUTPUT>(step);
return loopDecorator.Process(input);
}
}
- 最后,上层调用如下所示:
class Program
{
static void Main(string[] args)
{
var list = Enumerable.Range(0, 10);
foreach (var item in list.Step(new DoubleStep()))
{
Console.WriteLine(item);
}
}
}
总结#
通过上述 5 部分示例代码的不断改进,最终我们实现了一个支持依赖注入和条件式组装的管道,了解了如何进行管道式编程。掌握管道式编程可以让我们对整个项目的架构和代码质量都有很大帮助,感兴趣的朋友可以自行查阅相关资料进行深入研究。
相关参考#
赞赏#
日期 | 赞赏者 | 金额 | 备注 |
---|---|---|---|
2019-07-17 | *强建 | 10元(支付宝) | 希望结合 asp.net core 再出一个 |
Recommend
-
80
DotNetCore Is AnyWhere. 前言 Visual Studio 2019 已经正式发布了, DotNetCore 3.0 的正式版也指日可待。在之前的版本中,作为一名基于微软生态的传
-
46
介绍 由于历史原因,基于 Windows 平台存在着大量的基于 .NetFramework 开发的 WPF 和 WinForm 相关程序,如果将这些程序全部基于 DotNetCore 3.0 重写一遍
-
62
如何你希望你的 WPF 程序能够以 Windows 的保护机制保护起来,不被轻易反编译的话,那么这篇文章应该能帮到你。 介绍 MSIX 是微软于去年的 Windows 开发者日峰会 上推出的全新应用打
-
26
问题描述 在传统的基于 .NET Framework 的 WPF 程序中,我们可以使用如下代码段启动相关的默认应用: 但是上述协议方式在 .NET Core 中不再适用,当我们使用上述方式进行操作,程
-
47
-
35
-
23
▋****1. 管道的概念 管道,又名「无名管理」,或「匿名管道」,管道是一种非常基本,也是使用非常频繁的IPC方式。 1.1 管道本质 管道的本质也是一种文件,不过是伪文件,实际上是一块内核缓冲区,大...
-
10
ASP.NET Core应用基本编程模式[1]:管道式的请求处理 HTTP...
-
11
《Unix/Linux编程实践教程》笔记(9)──IO重定向和管道 Unix 默认规定程序从文件描述符0读取数据,写数据到文件描述符1,将错误信息输处到文件描述符2.这三个文件描述符称为标准输入,输出及标准错误输出。 创建系统描述符的系...
-
4
最近在对某个后端服务做 .NET Core 升级时,里面使用了多处处理 MultipartFormDataContent 相关内容的代码。这些地方从 .NET Framework 迁移到 .NET Core 之后的代码改动较大,由于本身没有测试覆盖,导致在部署 QA 环境后引发了一些问题。这里做一个技...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK