Why does a static constructor not have any parameters?

前端 未结 9 1541
忘掉有多难
忘掉有多难 2021-02-07 03:02

Per MSDN:

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to ini

9条回答
  •  星月不相逢
    2021-02-07 03:28

    Here is an example of a method for allowing nested classes to access Form controls WITHOUT PASSING THE FORM AS A PARAMETER TO THE NESTED CLASS' CONSTRUCTOR:

    public partial class Form1 : Form
    {
        public int nWow;
    
        public Form1()
        {
            InitializeComponent();
            Inner.AssignMe(this); // This is where the real action is.
        }
    
        class Inner
        {
            static Form1 Me;
    
            static Inner(){} // empty static constructor necessary
    
               // Called AssignMe in the Form1 constructor in this code, 
               // but this can be generalized to any nested class.
            public static void AssignMe(Form1 form) { Me = form; }
    
            public Inner() { Me.nWow = 1; } // Now u can access public Form1
        }                        // members and methods even from the nested
    }                            // class' constructor.
    

    I figured this out based on user3567816's message above, which, though terse and having 0 votes, is never the less by far the most elegant solution and very unique. No one else is giving this advise to this kind of question. NO MORE BUTT UGLY REDUNDANT FORM PARAMETERS IN CONSTRUCTORS OF NESTED CLASSES! This is absolutely brilliant!!

    I couldn't help but give a VB.Net twist with the use of the static variable name Me. Smirk.

提交回复
热议问题