Referencing non-static fields from static functions and vice versa impossible?

前端 未结 2 371
迷失自我
迷失自我 2021-01-22 16:46

I want to programmatically determine the space I\'ve got for some controls I want to create dynamically. So, I want to get the container\'s height and divide it by the number of

相关标签:
2条回答
  • 2021-01-22 17:04

    pass dynamicPanel as parameter to static method

    public partial class CRLoginsMainForm : Form {
    
      int controlHeight = getControlHeightToUse(dynamicPanel);
    

    change getControlHeightToUse as below

    private static int getControlHeightToUse(Panel panel) {
      return (panel.Height / NUMBER_OF_ROWS);
    }
    

    if you want to call non static method from static method you can do as below

    public class Foo
    {
        // public method 
        public void Method1()
        {
        }
    
        public static void Data2()
        {
            // call public method from static method
            new Foo().Method1();
    
        }
    }
    
    0 讨论(0)
  • 2021-01-22 17:26

    A static method has only direct access to static memebers of the class, if you want to use instance members of the class, you must pass in an instance of the class to the method (or have one available as a static as in the case of a singleton).

    Thus, you can modify your method to take in the instance member that is preventing it from being able to be static:

    private static int getControlHeightToUse(Panel thePanel) 
    {
      return (thePanel.Height / NUMBER_OF_ROWS);
    }
    

    Then just pass in dynamicPanel on the call...

    Instance methods, however, can access static members. Remember that static members are shared among all instances and exist even if no instance of the class exist. Thus they can't call instance members since they don't know which instance you are talking about.

    0 讨论(0)
提交回复
热议问题