This is probably a dumb question but I'm going to ask it anyways... I am programing in C#.NET. I have a class that contains a non-static, instance EventHandler. Is it possible to trigger that EventHandler for every instance of the class that exists from a static method?? I know this is a long shot!
The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs.
Static methods are class methods, and non-static methods are methods that belong to an instance of the class. Static methods can access other static methods and variables without having to create an instance of the class.
Non-static variables are part of the objects themselves. To use a non-static variable, you need to specify which instance of the class the variable belongs to. ... In other words, non-static data cannot be used in static methods because there is no well-defined variable to operate on.
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.
You can do this, but you'll need to create a static collection of all your objects:
public class Thing
{
public static List<Thing> _things = new List<Thing>();
public Thing()
{
_things.Add(this);
}
public static void SomeEventHandler(object value, EventHandler e)
{
foreach (Thing thing in _things)
{
// do something.
}
}
}
You'll want to watch out for accumulating too may "Things" . Make sure you remove them from the list when you don't need them anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With