如何在 F# 中使用 C# 对象?

18

我有以下的C#代码。

namespace MyMath {
    public class Arith {
        public Arith() {}
        public int Add(int x, int y) {
            return x + y;
        }
    }
}

我想出了名为testcs.fs的F#代码来使用这个对象。

open MyMath.Arith
let x = Add(10,20)

当我运行以下命令时:

fsc -r:MyMath.dll testcs.fs

我收到了这个错误信息:

/Users/smcho/Desktop/cs/namespace/testcs.fs(1,13): error FS0039: The namespace 'Arith' is 
not defined
/Users/smcho/Desktop/cs/namespace/testcs.fs(3,9): error FS0039: The value or constructor 'Add' is not defined

可能出了什么问题? 我在使用针对.NET的mono环境。

3个回答

18

尝试

open MyMath
let arith = Arith() // create instance of Arith
let x = arith.Add(10, 20) // call method Add

Arith在你的代码中是一个类名,你不能像命名空间一样打开它。 你可能对能够打开F#模块以便可以无需限定地使用其函数而感到困惑。


7

由于 Arith 是一个类而不是命名空间,所以您无法打开它。 您可以使用以下方法代替:

open MyMath
let x = Arith().Add(10,20)

3

使用 open 关键字,你只能打开命名空间和模块(类似于 C# 的 using 关键字)。 命名空间使用 namespace 关键字定义,在 C# 和 F# 中的作用相同。然而,模块实际上只是静态类,拥有仅为静态成员 - F# 只是将其隐藏。

如果你使用反编译器查看 F# 代码,你会发现你的模块已被编译为静态类。 因此,在 F# 中,你只能使用静态类作为模块。在你的示例中,该类不是静态的,所以为了使用它,你需要创建一个对象实例 - 就像在 C# 中一样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接