如何使用F#中的C#对象?
我有以下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):错误FS0039:命名空间'Arith'是 没有定义的 /Users/smcho/Desktop/cs/namespace/testcs.fs(3,9):错误FS0039:值或构造函数 “添加”未定义
可能有什么问题? 我使用mono for .NET环境。
尝试
open MyMath let arith = Arith() // create instance of Arith let x = arith.Add(10, 20) // call method Add
您的代码中的Arith是类名,您无法像命名空间一样打开它。 可能您对打开F#模块的能力感到困惑,因此可以无限制地使用其function
由于Arith
是一个类而不是命名空间,因此无法打开它。 你可以这样做:
open MyMath let x = Arith().Add(10,20)
使用open,您只能打开命名空间是模块(类似于C#using keyword)。 命名空间使用namespace关键字定义,在C#和F#中的行为相同。 但是,模块实际上只是静态类,只有静态成员 – F#只是隐藏了你。
如果您查看带reflection器的F#代码,您将看到您的模块已编译为静态类。 因此,您只能将静态类用作F#中的模块,并且在您的示例中,该类不是静态的,因此为了使用它,您必须创建一个对象实例 – 就像您在C#中所做的那样。