开发者

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 "));
    }
}
开发者_StackOverflow

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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜