user2316771
user2316771

Reputation: 149

Invoke abstract class method using reflection c#

My external dll design looks like :

class Engineering
{
   ProjectsCollection project {get;}
}

abstract class ProjectsCollection
{
   public abstract Project Open(string path);
}

I'm able to proceed till getting the method info

MethodInfo info = type.GetMethod("Open");

How to invoke the method "Open"?

Upvotes: 0

Views: 2587

Answers (2)

Sweeper
Sweeper

Reputation: 270980

Just call Invoke!

info.Invoke(someObject, new object[] {"This is the parameter of the method"});

Simple as that!

The return value of Invoke will be the return value of Open, which should be a Project object.

From the docs:

Invokes the method or constructor represented by the current instance, using the specified parameters.

Oh, and you should know that someObject above is the object that you're calling the method on. You should always make it an instance of a concrete class! Don't give it null!

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

Reflection or not, you cannot invoke an abstract method, because there is nothing to invoke. Sure, you can write

info.Invoke(eng.project, new object[] {path});

but it will throw an exception unless eng.project is set to an object of a non-abstract class descendent from ProjectCollection, which implements the Open method:

class ProjectsCollectionImpl : ProjectsCollection {
    public Project Open(string path) {
        return ...
    }
}

Engineering eng = new Engineering(new ProjectsCollectionImpl());
MethodInfo info = type.GetMethod("Open");
var proj = info.Invoke(eng.project, new object[] {path});

Upvotes: 1

Related Questions