简体   繁体   中英

How do I call a non-static method from a static method from a different class?

I would like to call a non-static method from a static method located in a different class. I know the instance of the class from which I would like to call the method from but I am not able to access it.

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        Helper _Helper = new Helper(this);
    }
    public void DoSmth(string input)
    {
        Console.WriteLine(input);
    }
}

public class Helper
{
    MainForm _mainform = null;

    public Helper(MainForm mainform)
    {
        _mainform = mainform;
        _mainform.DoSmth("test"); //ok
    }
    public static void Test ()
    {
        _mainform.DoSmth("test"); //generates error
    }
}

You can not access non static context inside static context.

You can make _mainform static

static MainForm _mainform = null;

or pass the instance you want to test to Test method

public static void Test(MainForm mainForm)
{
    mainForm.DoSmth("test"); 
}

or make Test non static

public void Test()
{
    _mainform.DoSmth("test"); 
}

All aside you should revise your design. Think about these questions. If I have a static method why it should access an instance member? If a method should access instance members then why should it be static?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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