在C#中,有没有办法通过插件覆盖私有或公共函数?
我有一个加载插件的应用程序。我有一个插件,可以完全访问表单实例。如果我有一个需要重写的函数,但它不是一个虚拟函数,有没有其他方法来重写它 下面是一个非常通用的示例:在C#中,有没有办法通过插件覆盖私有或公共函数?,c#,plugins,overriding,member-functions,C#,Plugins,Overriding,Member Functions,我有一个加载插件的应用程序。我有一个插件,可以完全访问表单实例。如果我有一个需要重写的函数,但它不是一个虚拟函数,有没有其他方法来重写它 下面是一个非常通用的示例: //Form I am modifying public partial class MyForm : Form { public int myVariable1; public int myVariable2; //Constructor and other methods here priva
//Form I am modifying
public partial class MyForm : Form
{
public int myVariable1;
public int myVariable2;
//Constructor and other methods here
private void setVar(int replacementValue)
{
myVariable1 = replacementValue;
}
}
…然后在一个单独的dll中
//My plugin
public class MyPlugin : IMyPluginBase
{
MyForm theForm; //Reference to the form in the main application
//Constructor and other methods here
private void setVar(int replacementValue)
{
theForm.myVariable2 = replacementValue;
}
}
在本例中,表单中的函数设置为“myVariable1”,而插件中的“setVar”函数设置为“myVariable2”
因此,问题是,在这个例子中,我可以用插件中的函数替换/覆盖表单的“setVar”函数吗?可能是通过消息或反射?您的问题的简短答案是否定的。但是,您可以做的是给表单一份IMyPluginBase的副本,并让form.setVar()调用MyPluginBase.setVar() 代码将如下所示:
public partial class MyForm : Form
{
public int myVariable1;
public int myVariable2;
public IMyPluginBase MyPlugin;
//Constructor and other methods here
private void setVar(int replacementValue)
{
MyPlugin.setVar(replacementValue);
//myVariable1 = replacementValue;
}
}
public class MyPlugin : IMyPluginBase
{
MyForm theForm; //Reference to the form in the main application
public void setVar(int replacementValue)
{
theForm.myVariable2 = replacementValue;
}
}
请注意,setVar()需要在IMyPluginBase中定义。否。不能在C#中“替换”或覆盖私有非虚拟方法。
C语言(和.NET运行时)不支持以您描述的方式动态替换方法。据我所知,很少有语言支持这种功能(我相信SmallTalk和Objective-C都支持)
如果这是应用程序中唯一需要这种可扩展性的地方,那么可以通过接口、委托或inhertance+虚拟方法来实现。这些方法中的任何一种都可能奏效。。。您选择哪一个取决于您想要什么样的可扩展性
如果您希望在应用程序中有许多这样的扩展点,那么您可能应该看看(MEF)。它提供了一个Microsoft支持的模型,用于使用在.NET中运行良好的模式和技术创建插件体系结构。如果某个函数未标记为类实现的或其一部分,则完全没有可能重写它。没有插件,没有反射,什么都没有,干脆忘了它,或者使用其他动态语言,而不是C#。我应该指出,这个精确的实现只允许每个表单有一个插件。表单上的IMyPluginBase列表可以解决这个问题。您可以使用MEF编写插件,使主应用程序对插件一无所知吗?我们有一个加载插件的应用程序,但不知道插件的类型或方法,只知道我们定义的公共“IPlugin”接口。我们需要保持这种方式。@Mike Webb:MEF确实要求支持可扩展性的应用程序公开其扩展点。这意味着您可以扩展原始应用程序的方式受到作者选择允许的内容的限制(您不能对原始代码的操作方式进行任意更改)。但是,应用程序不必事先知道它将使用的扩展。它只需要在前面提供扩展点。根据您所描述的,我认为MEF可能是一个很好的选择。通过分析API可以实现这一点,但如果您走这条路,您会感到头疼。插件可以“做任何事情”的整个概念都不符合隔离原则,隔离原则在维护开发人员的理智方面起着重要作用。