返回元组

来源:互联网 发布:用循环给二维数组赋值 编辑:程序博客网 时间:2024/05/29 15:30
返回元组


首先,我们讨论为什么应该避免使用元组。如果函数返回元组,用户就必须引用  FSharp.Core.dll;另外,需要使用元组的代码C# 中看并不好。考虑下面的例子,我们定义了函数 hourAndMinute,它从结构 DateTime 中返回时、分。


#light
module Strangelights.DemoModule
open System


// returns the hour and minute from the give date as a tuple
let hourAndMinute (time: DateTime) = time.Hour, time.Minute


// returns the hour from the given date
let hour (time: DateTime) = time.Hour
// returns the minutes from the given date
let minute (time: DateTime) = time.Minute


为了从 C# 中调用这个函数,还要跟着完成下面的例子。如果你使用 Visual Studio,需要在 F# 解决方案中创建一个 C# 项目,即,选择 文件-添加-新建项目,再选择 C# 控制台项目,如图 14-1 所示。


 
图 14-1 如何新建 C# 项目
接下来,需要在 C# 项目中添加对 F# 项目的引用,然后,添加下面的 C# 类到刚创建的项目中。


// !!! C# Source !!!
using System;
using Strangelights;
using Microsoft.FSharp.Core;


static class PrintClass {
  internal static void HourMinute() {
    // call the "hourAndMinute" function and collect the
    // tuple that's returned
    Tuple<int, int> t = DemoModule.hourAndMinute(DateTime.Now);
    // print the tuple's contents
    Console.WriteLine("Hour {0} Minute {1}", t.Item1, t.Item2);
  }
}


示例的运行结果如下:


Hour 16 Minute 1


虽然前面示例中的 C# 并不太难看,但是,如果把这个函数分成两个,一个返回小时,一个返回分钟,可能会更好。
0 0
原创粉丝点击