需要在 C# 中定义接口的帮助
我有一个数据驱动的地图应用程序,我需要将自定义功能作为插件实现。 我需要执行的自定义方法的名称也将在映射数据中。 我知道我可以使用 invoke 命令调用该方法; 但是,我如何确保每个方法都有适当的签名?
I have a data driven mapping application where I need to implement custom functions as plugins. The name of the custom method that I need to execute will also be in the mapping data. I know that I can call the method using the invoke command; but, how can I ensure that each method has the appropriate signature?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,我认为您不应该允许重写方法的任意名称 - 只需定义一个接口并保持简单即可。
您可以定义一个带有方法的接口,该方法将委托返回到执行该工作的方法。
否则,您只需使用反射来获取映射方法的 MethodInfo 并在运行时检查它是否具有正确的签名。
First of all I don't think you should allow arbitrary names for the overridden methods - just define an interface and keep it simple.
You could define an interface with a method that returns a delegate to the method that does the work.
Otherwise, you will just have to use reflection to get the MethodInfo for the mapped method and check at runtime that it hasd the correct signature.
通常,在开发插件架构时,您可以定义一个接口,其中包含将在插件上调用的方法。 需要插件来实现该接口。 当您加载它时,您将其强制转换为接口(如果没有实现它,则会失败)并在代码中将其用作接口。 如果插件的行为更通用,您只需更通用地定义接口,例如使用配置来建立插件的参数,然后使用不带参数的简单方法来调用插件的功能。 我认为您会发现使用预定义的界面更容易,并且它不应该对您造成太多限制。
Typically, when developing a plugin architecture, you define an interface with the methods that you will invoke on the plugin. The plugin is required to implement the interface. When you load it you cast it as the interface (if it doesn't implement it, this will fail) and use it in your code as the interface. If the behavior of the plugin is more generic, you simply define your interface more generically, for example using configuration to establish the plugin's parameters and then using a simple method without arguments to invoke the plugin's functionality. I think you'll find it easier to work with a pre-defined interface and it shouldn't limit you too much.
您将不得不使用反射。
您首先必须调用 GetMethod( ) 方法以获取 MethodInfo 相关方法的对象。
然后您需要使用
.GetParameters( )
方法来获取该方法的参数,然后您需要将这些参数与您期望该方法具有的参数进行比较。You will have to use reflection.
You will first have to call the GetMethod() method in order to get the MethodInfo object for the method in question.
Then you need to use the
.GetParameters()
method to get hold of the parameters to the method, then you need to compare those against what you expect the method to have.