C#WPF项目无法调用F#库

Ste*_*ion 4 .net wpf f#

最近我从我当前的项目中休息了2周,写了一个体面的文件解析器和一个数字错误检查器.我决定用F#写它们,因为踢腿和咯咯笑.神奇的决定.

用VB编写的旧版程序超过1000行; 我在F#中用170管理它.真棒.

我现在回到我当前的项目,并希望合并一个F#lib来进行一些解析,并可能编写/读取XML保存文件.但我似乎无法弄清楚如何在我的生命中从C#WPF应用程序调用F#库.

我正在使用Microsoft Visual 2010 Professional,这是我迄今为止参考这篇文章的尝试:http://www.devjoy.com/2013/02/c-to-f-interop-sharing-a-domain-model / 和几个SO帖子:

  1. 创建一个WPF项目.
  2. 在解决方案中添加了一个F#库项目.
  3. 通过以下方式向C#项目添加了对F#库的引用:右键单击SolutionExplorer中的项目文件,单击"添加引用",从"项目"选项卡中选择"MyFSharpLib",然后单击"添加".
  4. 然后我将一些测试代码添加到默认的F#文件module1.fs中:

    module Module1
    
    let Add a b = a + b
    
    Run Code Online (Sandbox Code Playgroud)
  5. 并尝试从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);
    }
    }
    }
    
    Run Code Online (Sandbox Code Playgroud)

这会导致错误说:"当前上下文中不存在名称'Module1'."

我认为问题在于装配体.我注意到我见过的几个代码示例using Microsoft.FSharp.Core.这是我悲伤的根源吗?我尝试添加它,但无法在.NET选项卡下找到它.

这让我发疯,任何帮助都会非常感激.

Jac*_* P. 5

看起来你已经找到了答案 - 构建F#项目 - 但是我将为一个问题提供答案(后代),这个问题几乎具有完全相同的症状,但却有不同的根本原因.

如果您使用完全按照提供的示例F#代码,即具有简单名称(没有命名空间)的模块,那么global在从C#访问F#模块时需要知道需要使用关键字,这一点很重要.例如,这是您必须调用Add从C#定义的函数的方法:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = global::MyModule.Add(1, 2);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

除非你有特殊的理由不这样做,否则在你的模块中使用命名空间通常是个更好的主意,例如module MyNamespace.Module1.