小编Hob*_*bes的帖子

Cunc中的C#歧义+扩展方法+ lambdas

我一直试图通过这篇文章:

http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx

......第1页上的内容让我感到不舒服.特别是,我试图围绕Compose <>()函数,我为自己写了一个例子.考虑以下两个Func:

Func<double, double> addTenth = x => x + 0.10;
Func<double, string> toPercentString = x => (x * 100.0).ToString() + "%";
Run Code Online (Sandbox Code Playgroud)

没问题!很容易理解这两者的作用.

现在,按照本文中的示例,您可以编写一个通用的扩展方法来组合这些函数,如下所示:

public static class ExtensionMethods
{
 public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>(
  this Func<TFirstOutput, TLastOutput> toPercentString,
  Func<TInput, TFirstOutput> addTenth)
 {
  return input => toPercentString(addTenth(input));
 }
}
Run Code Online (Sandbox Code Playgroud)

精细.所以现在你可以说:

string x = toPercentString.Compose<double, double, string>(addTenth)(0.4);
Run Code Online (Sandbox Code Playgroud)

你得到字符串"50%"

到现在为止还挺好.

但这里有一些含糊不清的东西.假设您编写另一种扩展方法,现在您有两个函数:

public static class ExtensionMethods
{
 public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>(
  this Func<TFirstOutput, TLastOutput> toPercentString,
  Func<TInput, TFirstOutput> …
Run Code Online (Sandbox Code Playgroud)

c# generics monads extension-methods func

2
推荐指数
1
解决办法
1615
查看次数

标签 统计

c# ×1

extension-methods ×1

func ×1

generics ×1

monads ×1