简体   繁体   中英

OOP: instantiating a class containing a console method within a main method using C#?

In the C# code below, I am trying to execute the code in the consoleread method by instantiating it within the Main method. I am a complete beginner at OOP and it seems to work but I just want to be sure if this is the right way to do it?

using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;

namespace ConsoleApplication1
{
    class ConsoleRead
    {
        public void consoleread()
        {
            string[] sPorts = SerialPort.GetPortNames();
            foreach (string port in sPorts)
            {
                var serialPort = new SerialPort();
                serialPort.PortName = port;
                serialPort.Open();
                serialPort.WriteLine("ATI");
                var message = Console.ReadLine();
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ConsoleRead c = new ConsoleRead();
            c.consoleread();
        }
    }
}

Yes its the right way. But are you facing any problems in it?

Yes it's alright. You have a class with an instance method, so you instantiate that class and call the method against the instance.

Now, for the question "is this the right way to do", then it's a little hard to answer without more background. In your particular example, if the only goal of your application is to write some string on serial ports without any reusability concerns, then creating a class that is instantiated only once is probably useless, you should just move the code from your consoleread method to the main method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM