How can I reference a method from another class without instantiating it?
I don't want to create an object because it won't affect my visible f开发者_开发技巧orm. How can I call a method so it does its thing in the visible side of things.
public class foo
{
public void SetString(string foo)
{
label1.Text = foo;
}
}
Inside another class:
foo X = new foo();
X.SetString("testlololol");
This will set the label, but VIRTUALLY, I won't be able to see it on my form.
How can I do the same thing, but on my VISIBLE side of things?
When you create your visible form store a references to it in some static property. Then other classes can use that property to run public methods of that class.
// the original form
class MyForm()
{
// form public method
public void MyMethod() { ... }
}
// class storing the reference to a form
class MyOtherClass
{
public static Form MyForm;
public void ShowForm()
{
MyForm = new MyForm();
MyForm.Show();
}
}
// invoke form public method in this class
class YetAnotherClass
{
public void SomeMethod ()
{
MyOtherClass.MyForm.MyMethod();
}
}
You need to somehow get the instance which is visible. Work out some information path from things that already know about your form (or whatever it is) to your other code. Consider what would happen if there were two visible forms - which one would you want? That should suggest a way forward. If you know for a fact that there'll only ever be one visible instance, you could use a singleton - but I'd strongly suggest that you don't.
Bear in mind that you may not need to know of it by its full type name - if this is crossing layers, you may want to work out some interface including the action in some abstract way.
I would usually either pass a reference of my form ('foo' in this case) to the other class. Or I would store off a copy of 'foo' to some static location. If you know that there will only ever be 1 instance of 'foo' you could do something like:
public class foo
{
public static foo Current { get; private set; }
public foo()
{
foo.Current = this;
}
public void SetString(string foo)
{
label1.Text = foo;
}
}
...and...
foo.Current.SetString("testlololol");
Though thats a bit hacky IMO, and doesnt support multiple instances of 'foo'.
Your second class needs to have a reference to the instance of the class that IS visible.
public class OtherClass{
foo myFoo;
public OtherClass( foo visibleFoo )
{
myFoo = visibleFoo;
}
public void method()
{
myFoo.SetString("testlolol");
}
}
精彩评论