如前所述通過@Matthew斯賓塞你應該通過串口作爲參數傳遞給需要它的靜態方法。首先在你的主板類上創建一個方法,或者不管它的名字是什麼,都會返回你的串口實例。然後使用它來獲取用於您提到的靜態方法的串行端口。
像這樣的事情應該是你所需要的..
public bool Read_Board_Port()
{
byte[] bData = new byte[256];
string message;
bool sucess = false;
try
{
if (!(serialBoardPort.IsOpen == true))
Connect_To_Board(Globals.BoardportName, Globals.BoardbaudRate, Globals.Boardparity, Globals.BoardstopBits, Globals.BoarddataBits);
if(CMDDirect || Globals.HostCommandString)
{
serialBoardPort.ReadTimeout = 1000; // Timeout if no answer from the port.
message = serialBoardPort.ReadLine();
Globals.RXBoardBuff = Encoding.UTF8.GetBytes(message);
Write_To_Console_Dr(message);
sucess = true;
}
else
{
serialBoardPort.Read(Globals.RXBoardBuff, 0, Constants.RXBOARDBUFFSIZE);
if (Check_Command_Correct(Globals.RXBoardBuff, Globals.CommandOut))
sucess = true;
else
{
Write_Error_To_Console_Dr(Constants.ERRORDATAFROMBOARDPORT);
sucess = false;
}
}
}
catch
{
MessageBox.Show(Constants.ERRORNODATABOARPORT);
sucess = false;
}
return sucess;
}
// since serialBoardPort seems to be a globally declared variable
public SerialPort GetInstance()
{
return serialBoardPort;
}
// Let's name your class as board..
// on somewhere in your app code:
Board board = // GetValue
SerialPort boardSerialPort = board.GetInstance();
ClassXXX.StaticMethodNeedsPort(boardSerialPort); // pass your serial port to the static method
UPDATE:既然有一點誤解的提問說..
我建議使用IoC容器,閱讀更多here
這是我使用的。通常這已經是框架的一部分,如MVVM Cross。
CODE:
public class Core
{
private static readonly Core instance = new Core();
private Dictionary<Type, object> container;
private Core()
{
container = new Dictionary<Type, object>();
}
public void RegisterSingleton<T>(T value) where T : class
{
Type type = typeof(T);
if (!container.ContainsKey(type))
container.Add(type, value);
}
public T GetSingleton<T>() where T : class
{
Type type = typeof(T);
if (container.ContainsKey(type))
return (T)container[type];
else
throw new Exception("Singleton instance not registered.");
}
public void RemoveSingleton<T>() where T : class
{
Type type = typeof(T);
if (container.ContainsKey(type))
container.Remove(type);
}
public void ClearSingletons()
{
container.Clear();
}
public static Core Instance
{
get { return instance; }
}
}
當你的應用程序加載加入這一行:
Core.Instance.ClearSingletons();
在情況下,它已經在裝載端口,因爲它是由C#自動生成剛註冊實例太..
Core.Instance.RegisterSingleton(MySerialPortObject); // Or class. Can be object
在應用程序的一部分,當你需要的端口只是得到它的instanc e像這樣...
SerialPort _myPort = Core.Instance.GetSingleton<X>(); // Where X value is the type of your registered object. If you are registering a SerialPort then replace X with SerialPort.
你可以在任何你喜歡的地方獲得你的端口實例。當我使用這個我通常註冊實施的接口,這樣我可以得到它喜歡
IFileHandler _fileHandler = Core.Instance.GetSingleton<IFileHandler>() // Where I registered the class that implements IFileHandler upon the startup of my application
對不起,長的答案。
如果您確實需要使用靜態方法,只需將一個參數添加到包含串行端口對象的靜態方法中即可。我會推薦使用非靜態方法。 –
謝謝,我不確定我完全理解你的建議。該端口是用VS設計器生成的,我怎樣才能添加串口對象並在哪裏? – Sharon