How does one access a control from a static method?

前端 未结 10 1943
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 12:50

I have an application in C# .NET which has a MainForm and a few classes.

One of these classes receives incoming data messages from a network. I need to

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 13:30

    Seeing as you are new to C# I will keep this as simple as possible. You should have a Program.cs file that has a single method Main (this would have been generated by Visual Studio). You will need to make it look like the following:

    class Program
    {
        public static readonly MainForm MainForm;
    
        static void Main()
        {
            Application.EnableVisualStyles();
            MainForm = new MainForm(); // These two lines
            Application.Run(MainForm); // are the important ones.
        }
    }
    

    Now in your incoming message you will have a way to access that form.

     public void IncomingMessage(IncomingMessageType message)
     {
          Program.MainForm.RecieveMSG(message);
     }
    

    That method in the form would then be a instance (not static) method. E.g.

     public void RecieveMSG(IncomingMessageType message) // NB: No static
     {
         txtDisplayMessages.Text = message.Text; // Or whatever.
     }
    

    There are better ways to do it - but as a beginner I think this would be the best approach.

    The difference between static and instance (instance is when you don't say static) is huge. To get to an instance method, field or property (which are collectively called members in C#) you need to have the containing instance. So:

     Person p = new Person(); // You now have an instance.
     p.Name = "Fred"; // You are using an instance property.
    

    Static are the opposite, they are the same anywhere in your application (more technically within the same AppDomain - but if you are a beginner you won't need to worry about that for a while). You don't need an instance to get to them (props to codewidgets "Static methods can access only static members"). For example:

     // Where Planet is a class and People is a static property.
     // Somewhat confusingly the Add method is an instance - best left for the student :).
     Planet.People.Add(new Person("Fred")); 
    

    Hopefully that gives you a good indication of what static and instance is and where to use them. The most important thing though is to try and avoid static members as best as you can - they can cause maintenance nightmares.

    Microsoft has a whole write-up on the important concepts in regard to this.

提交回复
热议问题