简体   繁体   中英

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"?

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});

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM