问题描述:

I have windows form which is calling another class's method and need to be passed as parameter.

public partial class Form1 : Form

{

private myClass _myClass;

public Form1()

{

InitializeComponent();

_myClass = new myClass(//pass this instance - Form1 - as parameter)

}

}

But I don't know how to pass Form1 instance as parameter? I need to do this, because this other class is creating system tray icon and menu strip and is able to close the parent form.

网友答案:

You'd just do:

_myClass = new myClass(this);

And then change the constructor in myClass:

public class myClass
{
    private Form1 theForm;

    public myClass(Form1 theForm)
    {
        this.theForm = theForm;
    }

    ...
}

Now you can access the form from within the class. I think I'd avoid doing this though. Try to leave the form in charge of calling the class and determining when it should close itself.

Having the class hold a reference back to the form that instantiated it, and closing it from within the class seems like it could lead to confusion and maintainability issues down the road.

网友答案:

Sure you can:

_myClass = new myClass(this);
网友答案:

I can't figure out what you want to achieve. but if you just want to pass this form than you can use this.

_myClass = new myClass(this);
网友答案:

Simply declare a parameter of type Form in the other's class constructor:

public class myClass
{
    private Form otherForm;

    public myClass(Form form) 
    {
        otherForm = form;
    }
}

and call it from within Form1:

_myClass = new myClass(this);
网友答案:

Unless I'm missing something, this ought to be fairly straightforward:

    public Form1(myClass instance)
    {
        InitializeComponent();
        _myClass = instance;
    }
相关阅读:
Top