[英]OOP: instantiating a class containing a console method within a main method using C#?
在下面的C#代碼中,我試圖通過在Main
方法中實例化它來在consoleread
方法中執行代碼。 我在OOP是一個完全的初學者,它似乎工作,但我只是想確定這是否是正確的方法呢?
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();
}
}
}
是的,它是正確的方式。 但是你面臨任何問題嗎?
是的,沒關系。 您有一個帶有實例方法的類,因此您實例化該類並針對該實例調用該方法。
現在,對於“這是正確的做法”這個問題,如果沒有更多的背景,那么有點難以回答。 在您的特定示例中,如果應用程序的唯一目標是在串行端口上編寫一些字符串而沒有任何可重用性問題,那么創建僅實例化一次的類可能是無用的,您應該只將代碼從consoleread
方法移動到main
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.