我为我的一个程序创建了自己的插件架构。

基本插件是我所有插件的基类,并说我的插件等插件:插件:插件,插件:插件。

public class Plugin 
{
    private static Plugin _instance;
    public static Plugin Instance { get { return Plugin._instance; } }
}

现在,像往常一样,我的每个插件都有其他内容,例如表单和其他类。从该类中,我想访问当前插件实例;

Plugin.Instance.Settings()

如果我确实在插件ctor中分配了_instance字段;

public Plugin(GlobalSettings gs, PluginSettings ps)
{
    Plugin._instance=this;
}

然后,对于每个已加载的插件,实例都被覆盖,我将获得奇怪的结果,例如插件。

我知道Singleton似乎不是做到这一点的正确方法,但是我无法提供另一个解决方案。也许Multiton可以解决这个问题,但我不希望我的插件作家去找

Plugin.Instance["PluginB"] 

一直以来似乎无关紧要。

谢谢你的帮助。

有帮助吗?

解决方案

如建议的,您应该将它们存储在某种列表中,可能是在托管应用程序中或库中。

您已经有一个引用当前插件的引用,并带有“此”关键字,只需通过构造函数或方法将其传递到其他类中:

喜欢

public class MyPlugin :Plugin
{
    private MyClass myClass;

    public MyPlugin()
    {
         this.myClass = new MyClass(this);  
         this.myClass.DoSomething();
    }
    public void Something()
    {
         //Called back into from MyClass

    }
}
public class Myclass
{
     public Plugin OwnerPlugin {get;internal set;}
     public MyClass(Plugin ownerPlugin)
     {
           this.OwnerPlugin = ownerPlugin;
     }
     public void DoSomething()
     {
          //do something with ownerplugin
          this.OwnerPlugin.Something();
     } 
}

其他提示

去除 static 关键字并保留 List<Plugin> 循环绕过它们。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top