最近我从我的项目中暂停了2周的时间来编写一个体量不小的文件解析器和数值误差检查器。出于兴趣,我决定用F#语言编写它们。这是一个很棒的决定。
以前用VB编写的程序超过1000行,在F#中只需170行就能搞定。太棒了。
现在我回到了我的项目中,想要使用一个F#库来完成一些解析工作并可能读写一个XML保存文件。但是我无论如何都无法弄清楚如何从C# WPF应用程序中调用一个F#库。
我正在使用Microsoft Visual 2010 Professional,并尝试参考这篇文章: http://www.devjoy.com/2013/02/c-to-f-interop-sharing-a-domain-model/ 还有一些stackoverflow的帖子:
- Create a WPF project.
- Added an F# library project to the solution.
- Added a reference to the F# library to C# project via: Right click project file in SolutionExplorer, click 'Add Reference', selected 'MyFSharpLib' from projects tab and click Add.
I then added some test code to the default F# file module1.fs:
module Module1 let Add a b = a + b
And tried to call it from C#:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } // Call F# library private void Button_Click(object sender, RoutedEventArgs e) { int a = Module1.Add(1, 2); } } }
这会导致出现错误,提示:“当前上下文中不存在名为'Module1'的名称。”
我认为问题出在程序集上。我注意到一些代码示例使用了using Microsoft.FSharp.Core
。这是否是问题所在?我尝试添加它,但在.NET标签下找不到它。
这让我很疯狂,请给予帮助,万分感谢。