简体   繁体   中英

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.

I've been trying to figure out how Modules and Namespaces work when used within a C# project. 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:

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. Trim is a static member of that class.

This is not caused by the way namespaces and classes behave in F#, you got that right.

The problem is that you have a namespace called File1 and a class called File1 . When you write File1 in your C# program, even if you have the correct using , it means “namespace File1 ”, not “class 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. (I'm not saying you should use naming like this in your actual project.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM