[英]Invoke abstract class method using reflection c#
My external dll design looks like : 我的外部dll设计如下所示:
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: 但除非将
eng.project
设置为ProjectCollection
的非抽象类后代的对象,否则该对象将实现Open
方法:
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
! 只需致电
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. Invoke
的返回值将是Open
的返回值,它应该是一个Project
对象。
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. 哦,您应该知道上面的
someObject
是调用方法的对象。 You should always make it an instance of a concrete class! 您应该始终使它成为具体类的实例! Don't give it
null
! 不要给它
null
!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.