Common Modules in F #

In C #, I can compile

static class Foo<T> { /* static members that use T */ } 

The result is general and not real.

What is the equivalent F # code? module<'a> does not compile, and type Foo<'a> is real.

+6
generics module f #
source share
2 answers

Other answers still have part of the image ...

 type Foo<'a> private() = // ' static member Blah (a:'a) = // ' printfn "%A" a 

great. Do not pay attention to what the reflector creates, you cannot create an instance of this class from the F # assembly (since the constructor is private), so this works well.

F # also allows you to create static constructors, the syntax is to include the expressions “static let” and “static do” in the class (which work in the same way that “let” and “do” work as part of the body of the main constructor, unless ) Full example:

 type Foo<'a> private() = // ' static let x = 0 static do printfn "Static constructor: %d" x static member Blah (a:'a) = // ' printfn "%A" a //let r = new Foo<int>() // illegal printfn "Here we go!" Foo<int>.Blah 42 Foo<string>.Blah "hi" 
+9
source share

At first I thought it would be close to what you wanted:

 type Foo<'a> private() = static member Blah (a:'a) = printfn "%A" a 

To be like the pre C # 2.0 idiom of being realistic only through reflection or the class itself (which I hope would not have done that).

however, this compiled to:

 [Serializable, CompilationMapping(SourceConstructFlags.ObjectType)] public class Foo<a> { internal Foo() {...} public static void Blah(aa) {...} } 

This means that other classes inside the f # assembly could instantiate.

However, the ever reported Brian pointed out that the f # compiler respects this private parameter, despite the CLR type, which means that the only way to create an instance will be through reflection or using something like the InternalsVisibleTo attribute.

This may be acceptable for your needs ...

+2
source share

All Articles