jeudi 6 août 2015

How to invoke method only from interface and method name?

In my program, we referenced another assembly, and there is an implement instance in that assembly definitely. So we want to invoke its method at run-time. We have known the interface and method name, but the implement instance name is not certainly. How I can invoke method only from interface and method name?

Type outerInterface = Assembly.LoadAssembly("AnotherAssemblyFile").GetTypes()
     .Single(f => f.Name == "ISample" && f.IsInterface == true);
Object instance = Activator.CreateInstance(outerInterface);
MethodInfo mi = outerInterface.GetMethod("SampleMethod");
var result = mi.Invoke(instance, new object[]{"you will see me"});

The exception is thrown:

An unhandled exception of type 'System.MissingMethodException' occurred in mscorlib.dll

Additional information: Cannot create an instance of an interface.

The referenced assembly code is here:

namespace AnotherAssembly
{
    public interface ISample
    {
        string SampleMethod(string name);
    }

    public class Sample : ISample
    {
        public string SampleMethod(string name)
        {
            return string.Format("{0}--{1}", name, "Alexsanda");
        }
    }
}

But the reflection part not work, I am not sure how I can make it work well.

Edit: I don't know the instance name clearly, only know the interface name and method name. But I know there is an implement class from the interface in that assembly definitely.





Aucun commentaire:

Enregistrer un commentaire