简体   繁体   English

从不同的命名空间和类调用方法

[英]Calling method from different namespace and class

I'm trying to put some stuff that I use a lot into separate classes so it's easier to implement when starting a new project. 我正在尝试将一些我经常使用的东西放到不同的类中,这样在开始一个新项目时更容易实现。

One of the things that I would like to do, is dynamically create a statusbar on my mainform. 我想做的其中一件事是在我的mainform上动态创建状态栏。 I have done this in a previous project and there it worked fine. 我在之前的项目中完成了这项工作,并且工作正常。 So I copied the code and I changed the NameSpace for the mainform. 所以我复制了代码并更改了mainform的NameSpace。

When I run the code it stops at the line 当我运行代码时,它停在该行

MainForm.Controls.Add(status);

When I look, it says Mainform is null. 当我看,它说Mainform是null。 Other than the Namespace I haven't changed anything. 除了命名空间,我没有改变任何东西。 Does anybody have an idea why this is happening? 有没有人知道为什么会这样?

Thanks Kenneth 谢谢Kenneth

//THIS IS THE SEPARATE CLASS    
public class Tools
    {
        public Form MainForm;


        public void setupForm()
        {
            // LINK THE FORM
            MainForm = myNamespace.Form1.MainForm;

            // CREATE A STATUSBAR
            StatusStrip status = new StatusStrip();
            status.Name = "status";

// I'VE REMOVED SOME OF THE DYNAMIC CREATION STUFF FOR READABILITY

            // ADD THE STATUSSTRIP TO THE FORM
            MainForm.Controls.Add(status);
        }

//THIS IS THE MAINFORM
public static Form1 MainForm;
        public myNameSpace.Tools tools;

        private void setupForm()
        {
            this.KeyPreview = true;

            // LINK THE TOOLS CLASS
            tools = new myNameSpace.Tools();

            // SETUP THE FORM
            tools.setupForm();
        }

You have to pass a refernece of your main form to the Tools class. 您必须将主表单的引用传递给Tools类。 You can do this when you initialize tools or when you call the method setupForm. 您可以在初始化工具或调用方法setupForm时执行此操作。 I implemented the second possibility for you: 我为你实现了第二种可能性:

//the call:
tools.setupForm(this);

//the implementation of the method
private void setupForm(Form1 MainForm)
{
   //your method code
}

The normal way to separate responsibility is to inject the object you want to affect - not hijack it with a hardcoded reference. 分离责任的正常方法是注入你想要影响的对象 - 而不是用硬编码的引用来劫持它。

Try injecting the form when you create your tools object: 在创建工具对象时尝试注入表单:

tools = new myNameSpace.Tools(this); tools = new myNameSpace.Tools(this);

Its null because you don't initiate or have a refference to the main window. 它为null,因为您没有启动或对主窗口进行引用。 You just create an alias for the namespace but not for the instance. 您只需为命名空间创建别名,但不为实例创建别名。

Pass the mainWondow as a parameter to the setupForm function. 将mainWondow作为参数传递给setupForm函数。 Then it will work. 然后它会工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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