jeudi 4 juin 2015

InvalidCastException when casting dynamically to interface

I have an interface defined in an assembly like this:

namespace HelloWorlder
{
    public interface IHelloWorld {
        string SayHello();
    }
}

In a seperate assembly I have another class defined as:

using HelloWorlder;

public class HelloWorld : IHelloWorld {
    string IHelloWorld.SayHello() {
        return "Hello, world!";
    }
}

Now trying to invoke this from F# Interactive I get an invalid cast exception, here is the code trying to consume this DLL:

#I __SOURCE_DIRECTORY__
#r "HelloWorlder.dll"

open System
open System.Reflection
open HelloWorlder




let asm = Assembly.LoadFrom(__SOURCE_DIRECTORY__ + "\\HelloWorld.dll")
let hwIns = asm.CreateInstance("HelloWorld") :?> IHelloWorld
let res = hwIns.SayHello()

From what I can see it should work, as an extra precaution you will see that I have implemented the interface IHelloWorld explicitly. I'm guessing that there is something that I'm missing but I cannot figure out why it's throwing a cast exception.





Aucun commentaire:

Enregistrer un commentaire