您当前的位置: 首页 > 

C#中面向对象编程中的函数式编程

发布时间:2019-08-15 09:52:02 ,浏览量:7

目录

介绍

面向对象编程中仿真的函数式编程技术

粒度不匹配

面向对象的函数式编程构造

相互关系函数式编程/面向对象程序设计

C#中的函数式编程集成

函数级别的代码抽象

操作组合

函数部分应用和局部套用

面向对象编程中的体系结构函数编程技术

一些经典的面向对象设计模式与函数编程

策略

命令

观察者

虚拟代理

访问者

总结

  • 下载源代码 - 8 KB
介绍

使用函数式编程来丰富面向对象编程的想法是陈旧的。将函数编程函数添加到面向对象的语言中会带来面向对象编程设计的好处。

一些旧的和不太老的语言,具有函数式编程和面向对象的编程:

  • 例如,Smalltalk和Common Lisp
  • 最近是Python或Ruby
面向对象编程中仿真的函数式编程技术

面向对象编程语言的实践包括函数编程技术的仿真:

  • C ++:函数指针和()运算符的重载
  • Java:匿名类和反射
粒度不匹配

函数编程和面向对象编程在不同的设计粒度级别上运行:

  • 函数/方法:小程序编程
  • 类/对象/模块:大规模编程

至少有两个问题:

  • 我们在面向对象的编程体系结构中如何定位各个函数的来源?
  • 我们如何将这些单独的函数与面向对象的编程体系结构联系起来?
面向对象的函数式编程构造

C#提供了一个名为delegate 的函数编程函数:

delegate string StringFunType(string s); // declaration

string G1(string s){ // a method whose type matches StringFunType
  return "some string" + s;
}

StringFunType f1;    // declaration of a delegate variable
f1 = G1;             // direct method value assignment
f1("some string");   // application of the delegate variable

Delegate是一流的值。这意味着delegate类型可以键入方法参数,并且delegate可以作为任何其他值的参数传递:

string Gf1(StringFunType f, string s){ [ ... ] } // delegate f as a parameter
Console.WriteLine(Gf1(G1, "Boo"));   // call

Delegate可以作为方法的计算返回。例如,假设G是一个string=> string类型的方法,并在SomeClass中实现:

StringFunType Gf2(){ // delegate as a return value
  [ ... ]
  return (new SomeClass()).G;
}

Console.WriteLine(Gf2()("Boo")); // call

Delegate可以发生在数据结构中:

var l = new LinkedList(); // list of delegates
[ ... ]
l.AddFirst(G1) ;                         // insertion of a delegate in the list
Console.WriteLine(l.First.Value("Boo")); // extract and call

C#delegate可能是匿名的:

delegate(string s){ return s + "some string"; };

匿名delegate看起来更像lambda表达式:

s => { return s + "some string"; }; 
s => s + "some string";
相互关系函数式编程/面向对象程序设计

扩展方法使程序员能够在不创建新派生类的情况下向现有类添加方法:

static int SimpleWordCount(this string str){
  return str.Split(new char[]{' '}).Length;
}

string s1 = "some chain";
s1.SimpleWordCount(); // usable as a String method
SimpleWordCount(s1);  // also usable as a standalone method

扩展方法的另一个例子:

static IEnumerableMySort(this IEnumerableobj) where T:IComparable{
  [ ... ]
}

ListsomeList = [ ... ];
someList.MySort();

扩展方法在C#中有严格的限制:

  • 只有静态
  • 不是多态的
C#中的函数式编程集成

C#为参数数量提供函数和程序泛型delegate预定义类型,最多16个:

delegate TResult Func();
delegate TResult Func(T a1);
delegate TResult Func(T1 a1, T2 a2);
delegate void Action(T a1);
[ ... ]

一个delegate本身可以包含delegate 的调用列表。当调用这样的delegate时,delegate中包含的方法将按照它们在列表中出现的顺序被调用。结果值由列表中调用的最后一个方法确定。

C#允许将lambda表达式表示为称为表达式树的数据结构:

Expression            
关注
打赏
1688896170
查看更多评论

暂无认证

  • 7浏览

    0关注

    115984博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0537s