CSharpFunctionalExtensions -函数式编程C#的功能扩展
简介
该库有助于以更实用的方式编写代码
安装
在NuGet上可用
dotnet add package CSharpFunctionalExtensions
或者
PM> Install-Package CSharpFunctionalExtensions
例子
Maybe
创建一个值
Maybe<string> apple = Maybe<string>.From("apple");
// or
Maybe<string> apple = Maybe.From("apple"); // type inference
// or
var apple = Maybe.From("apple");
GetValueOrDefault
void Response(string fruit)
{
Console.WriteLine($"It's a {fruit}");
}
Maybe<string> apple = "apple";
Maybe<string> unknownFruit = Maybe<string>.None;
string appleValue = apple.GetValueOrDefault("banana");
string unknownFruitValue = unknownFruit.GetValueOrDefault("banana");
Response(appleValue); // It's a apple
Response(unknownFruitValue); // It's a banana
Where
bool IsMyFavorite(string fruit)
{
return fruit == "papaya";
}
Maybe<string> apple = "apple";
Maybe<string> favoriteFruit = apple.Where(IsMyFavorite);
Console.WriteLine(favoriteFruit.ToString()); // "No value"
Map
string CreateMessage(string fruit)
{
return $"The fruit is a {fruit}";
}
Maybe<string> apple = "apple";
Maybe<string> noFruit = Maybe<string>.None;
Console.WriteLine(apple.Map(CreateMessage).Unwrap("No fruit")); // "The fruit is a apple"
Console.WriteLine(noFruit.Map(CreateMessage).Unwrap("No fruit")); // "No fruit"
Select
Maybe<string> MakeAppleSauce(Maybe<string> fruit)
{
if (fruit == "apple") // we can only make applesauce from apples 🍎
{
return "applesauce";
}
return Maybe<string>.None;
}
Maybe<string> apple = "apple";
Maybe<string> banana = "banana";
Maybe<string> noFruit = Maybe<string>.None;
Console.WriteLine(apple.Bind(MakeAppleSauce).ToString()); // "applesauce"
Console.WriteLine(banana.Bind(MakeAppleSauce).ToString()); // "No value"
Console.WriteLine(noFruit.Bind(MakeAppleSauce).ToString()); // "No value"
如对函数式编程感兴趣的小伙伴,请前往Github查看官方文档
github地址
https://github.com/vkhorikov/CSharpFunctionalExtensions
如果大家喜欢我的文章,还麻烦给个关注并点个赞, 希望net生态圈越来越好!