Invoking non static method from static method
Can I call(access) non static method from static method ?? Like I have static method If yes, how??
public static void method() //like 开发者_Python百科this is a static method
{
methodsec(); //from here I want to access non static method defined below
}
public void methodsec() // non static method
{
}
Yes, but you need a reference to do it through:
public static void StaticMethod()
{
someInstance.InstanceMethod();
}
public void InstanceMethod()
{
}
You need to think about which instance you want to call the method on. Instance methods typically use the state of the instance, so the method is likely to do different things depending on which instance it's called on.
No you can't call it exactly like that. You either need an instance of the class to call the non-static method, or it also needs to be static.
An alternative approach would be to use a singleton pattern - so you only have one instance of the class available throughout your code, and don't need to use static methods. That way, all methods in the class can call each other. It's hard to tell whether this would actually suit your needs, without further info but could be the way to go
精彩评论