Access form method from another static class

So, now I almost do not understand, I'm not even sure if this is possible in the end. I have Visual C # Form, which is launched by the program Program.cs (The standard way - VS did all the setup work, of course).

In addition to this, I have a class with a static method in a separate C # file, because I like to keep one class in one file.

My form code has an open function:

public void print(String text) { rtb_log.appendText("\n" + text); } 

At a certain point in time, I call a static function from another class.

Is it possible to access this printing method from my other class? Since it refers to rtb_log (rich text field), it is available only in instanced case and, of course, is not static. But since static methods can only access static members, I have a bit of ideas here on how to add text to my form from another class.

Any help here?

+6
source share
2 answers

But since static methods can only access static members, I have a few of the ideas here on how to add text to my form from another class.

Static members can access instance members — they just need to know which instance the method can be called on. Therefore you can write:

 public static void Foo(OtherForm myOtherForm) { // Do some stuff... myOtherForm.Print(); // Case changed to comply with naming conventions } 

Then, when you call the method, you need to provide a link to the appropriate form. Basically, something should determine which instance you want to call Print on. Develop who has this information and pass it on from there. I would recommend not using a static variable to store this information. (A global state makes code less reusable, harder to reason about, and harder to test.)

EDIT: Given the comments, this sounds the way you want:

 // Within the form private void HandleClick(object sender, EventArgs e) { SomeClass.StaticMethod(this); } 
+7
source

See below

 class SomeMainClass { private ClassB form = null; private void SomeMethod() { form = new ClassB(); form.Show(); ClassA foo = new ClassA(this); } // Use an accessor. public ClassB Form { get { return this.form; } } } class ClassA { private SomeMainClass mainClass = null; // Constructor. public ClassA(SomeMainClass _mainClass) { this.mainClass = _mainClass; } private void SomeMethod() { this.mainClass.Form.Print("Something to print"); } } class ClassB : Form { // Constructor. public ClassB() { InitializeComponent(); } public void Print(String text) { rtb_log.appendText("\n" + text); } } 

Edit: This is a basic methodology in response to your comment. It is not so efficient in terms of resources, but it does what you want ...

Hope this helps.

+2
source

Source: https://habr.com/ru/post/919512/


All Articles