定义类和接口

定义类和接口

 

在 F# 中。有两种方式为函数和类的成员定义參数:“curried”风格,成员能够散(partially)应用,“元组(tuple)”风格。全部成员都必须一次给定。

定义类时。如使用元组风格,C# client能够更easy使用这种类。

看以下的样例,在 F# 中定义一个类,当中有一个curried 风格定义的成员CurriedStyle,另一个元组风格的TupleStyle。

 

namespace Strangelights

 

type DemoClass(z: int) =

  //method in the curried style

  memberthis.CurriedStyle x y = x + y + z

  //method in the tuple style

  memberthis.TupleStyle (x, y) = x + y + z

 

从 C# 中查看时。成员CurriedStyle 的签名是这种:

 

public FastFunc<int, int>CurriedStyle(int x)

 

而TupleStyle 则是这种签名:

 

public int TupleStyle(int x, int y);

 

因此,假设想要从 C# 中使用这两个成员,终于的代码会似这种:

 

// !!! C# Source !!!

using System;

usingStrangelights;

usingMicrosoft.FSharp.Core;

 

class Program {

  static voidUseDemoClass() {

   DemoClass c = new DemoClass(3);

    FastFunc<int,int> ff = c.CurriedStyle(4);

    int result = ff.Invoke(5);

   Console.WriteLine("Curried Style Result{0}", result);

    result= c.TupleStyle(4, 5);

   Console.WriteLine("Tuple Style Result{0}", result);

  }

  static void Main(string[] args) {

   UseDemoClass();

  }

}

 

从这个演示样例能够非常明显地看出,假设使用元组风格公开类的成员。库用户将会更惬意的。

在接口和类中指定抽象成员,要略微复杂一些。由于有几个很多其它的选择。

以下以样例说明:

 

namespaceStrangelights

 

type IDemoInterface =

  // method in the curried style

  abstract CurriedStyle: int-> int -> int

  // method in the tupled style

  abstract TupleStyle: (int* int) -> int

  // method in the C# style

  abstract CSharpStyle: int* int -> int

  // method in the C# style with named arguments

  abstract CSharpNamedStyle: x : int * y : int -> int

 

注意,OneArgStyle 和MultiArgStyle 之间唯一的不同是后者不使用括号。在 F# 定义中的这一点不同,对从 C# 中的签名却有非常大的影响。以下是前者的签名:

 

int OneArgStyle(Tuple<int, int>);

 

而后者的签名是这种:

 

int MultiArgStyle(int, int);

 

对 C# 用户来说,后者显然更加友好一些。然而。我们也要付出一些,为每一个參数加入名字。这并不改变 C# 用户使用的签名。当实现这种方法时,仅仅改变在用Visual Studio 工具实现接口时看到的名字。此外。一些其它的.NET 语言会把參数名看得非常重要。这听起来好像有点不同,可是,它使实现接口更加easy,由于,这样的实现方法可以更好地表达參数真正的意思。

以下的样例演示C# 代码实如今前面的样例中定义的接口IDemoInterface。非常明显。C# 用户更乐于接收包括由 MultiArgStyle 或 NamedArgStyle 指定的方法的接口。

 

// !!! C# Source !!!

using System;

usingStrangelights;

usingMicrosoft.FSharp.Core;

 

// shows how toimplement an interface

// that has been createdin F#

classDemoImplementation : IDemoInterface {

  // curried style implementation

  public FastFunc<int,int> CurriedStyle(intx) {

    // create a delegate to return

   Converter<int, int> d =

      delegate(int y) { return x + y; };

    // convert delegate to a FastFunc

    return FuncConvert.ToFastFunc(d);

  }

 

  // tuple style implementation

  public intTupleStyle(Tuple<int, int> t) {

    return t.Item1 + t.Item2;

  }

 

  // C# style implementation

  public intCSharpStyle(int x, inty) {

    return x + y;

  }

 

  // C# style implementation, named arguments

  // make no difference here

  public intCSharpNamedStyle(int x, int y) {

    return x + y;

  }

}

[

这一段描写叙述中的名字与实际代码不符,可是。并不影响对文章的理解,故未订正。

]

posted @ 2017-05-26 17:23  brucemengbm  阅读(188)  评论(0编辑  收藏  举报