[英]F# Namespaces/Modules and Interop with C#
I've been experimenting with F# and would like to try using it in a C# project for certain pieces of code that would benefit from the language. 我一直在尝试使用F#,并希望尝试在C#项目中使用它来处理某些可以从该语言中获益的代码。
I've been trying to figure out how Modules and Namespaces work when used within a C# project. 我一直试图弄清楚模块和命名空间在C#项目中的使用方式。 For example, the following code:
例如,以下代码:
namespace File1
#light
type File1(path : string) =
static member Trim(p : string) = p.Trim()
member self.Path = path
Then I try to use this in C# by saying: 然后我尝试在C#中使用它来说:
using File1;
class Program
{
static void Main(string[] args)
{
// Doesn't work
Console.WriteLine(File1.Trim(" hello "));
// Does work
Console.WriteLine(File1.File1.Trim(" hello "));
}
}
I understand why the second one works, but why doesn't the first one work? 我理解为什么第二个有效,但为什么第一个不起作用呢? I've pulled in the namespace with the using declaration and File1 should be a class.
我使用using声明引入了命名空间,File1应该是一个类。 Trim is a static member of that class.
Trim是该类的静态成员。
This is not caused by the way namespaces and classes behave in F#, you got that right. 这不是由命名空间和类在F#中的行为方式引起的,你做对了。
The problem is that you have a namespace called File1
and a class called File1
. 问题是你有一个名为
File1
的名称空间和一个名为File1
的类。 When you write File1
in your C# program, even if you have the correct using
, it means “namespace File1
”, not “class File1.File1
”. 在C#程序中编写
File1
时,即使using
正确,也表示“命名空间File1
”,而不是“类File1.File1
”。 If, for example, you changed the name of your namespace to FileNamespace
and the name of the type
to FileType
, everything would work as expected. 例如,如果您将名称空间的名称更改为
FileNamespace
,并将type
名称更改为FileType
,则所有内容都将按预期工作。 (I'm not saying you should use naming like this in your actual project.) (我不是说你应该在实际项目中使用这样的命名。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.