Type .GetType () does not work for type F # in C # code

I have an F # assembly called Assembly1

I have the following module:

namespace Assembly1 module MyModule = type MyClass(x: int, y: int) = new() = MyClass(0, 0) 

In the C # assembly that references this F # assembly, the following code gives me a "null" value back:

 var myType = Type.GetType("Assembly1.MyModule.MyClass, Assembly1"); 

Am I trying to make it impossible?

+5
source share
2 answers

Since you put MyClass in the module, it is compiled as a nested class. His name is Assembly1.MyModule+MyClass .

From C # you can load it like this:

 var myType = Type.GetType("Assembly1.MyModule+MyClass, Assembly1"); 

If you don't want to have nested classes (which are usually incredulous in C #), you can define them directly in the namespace:

 namespace Assembly1.LibraryXyz type MyClass(x: int, y: int) = class end 

This class will be named Assembly1.LibraryXyz.MyClass .

+5
source

To add to Mark the answer , it is also worth noting that many modules in F # are represented by different names in IL (and, therefore, non-F # languages), than they appear together with F # itself.

For example, this piece of code:

 open System open System.Reflection open Microsoft.FSharp.Reflection let private core = AppDomain.CurrentDomain.GetAssemblies() |> Seq.find (fun a -> a.GetName().Name = "FSharp.Core") let private seqMod = core.GetTypes() |> Seq.filter FSharpType.IsModule |> Seq.find (fun t -> t.FullName = "Microsoft.FSharp.Collections.SeqModule") 

Find the Seq module in FSharp.Core.

The FSharp.Reflection namespace has a bunch of helper methods that allow you to work with certain types of F # with System.Reflection a little less painful, so it's worth downloading a couple of assemblies in FSI and playing with them if you "I will do a lot of thinking with F # code .

You can create modules with "inappropriate" names, like this, using the CompiledName attribute - this is especially useful when you want a type and module with the same name. The usual convention (as shown with the Seq type / module) is to annotate the module with a compiled name.

 [<CompiledName("MyTypeModule")>] module MyType = let getString m = match m with | MyType s -> s 
+6
source

Source: https://habr.com/ru/post/1234251/


All Articles