简体   繁体   中英

How can I call a non-static method out of another class in C#?

The question itself sounds a bit nooby. To call a non static method from another class you have to use the current instance of the class. I tried to get the instance of the class with the method i want to call to the second class. I think I succeeded but it is still not working yet.

This one way how I tried to bring the instance to the second class:

arbeitsbearbeitung arbeitenbearbeitung = new arbeitsbearbeitung(arbeit);
arbeitenbearbeitung.Parent = this;
arbeitenbearbeitung.Show();

(out of Class 1)

And this is where I used it in class 2:

Form frm = (Form)this.Parent;
frm.updateGrid();

I also tried it with different ways like passing it as parameter; same result...

This is updateGrid() in class 1:

public void updateGrid()
{
    klassenarbeitenTableAdapter.Fill(this.database1DataSet.Klassenarbeiten);
}

It tells me that Form does not contain a definition for updateGrid .

I must be dumb but I can't find my mistake.

Thinking and googling for 2 hours and still no clue.

I feel dumb now. Thank you for your help!

you have to use the current instance of the class

You have to use an instance of the class. Not necessarily the current one.

I tried to get the instance of the class

There is not the instance (unless it's a singleton), there is an instance.

Next, Microsoft has implemented Form as part of the .NET framework. Microsoft's Form class does not have a updateGrid() method.

If you created a form, then that form inherits from Form and you added the method updateGrid() . So instead of casting to Form , cast it to your class.

So the code might read

arbeitsbearbeitung frm = (arbeitsbearbeitung) this.Parent;
frm.updateGrid();

Note that this is not clean code, since it breaks the Liskov substitution principle . But I think that's not your primary concern at the moment.

Form does not have an updateGrid method but your derived class does. You need to cast Parent to your class: MyForm frm = (MyForm)this.Parent;

You are declaring frm as a plain Form :

Form frm = (Form)this.Parent;

The problem is that the Form class has no function called updateGrid . When you say frm.updateGrid() , the compiler thinks "OK, frm is a Form , but Form doesn't have anything called updateGrid ". It doesn't know that frm will actually be your special subclass of Form with the updateGrid function defined.

Instead, you need to declare frm with the actual class of Class 1:

MyCustomForm frm = (MyCustomForm)this.Parent;

Then when you do frm.updateGrid() , the compiler will know what you're talking about.

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