我对编程很新, 很抱歉,如果我搞砸了一些话,我想这个问题可能真的很愚蠢。
无论如何,我正试图从另一个线程控制一个C#浏览器窗口。
该程序有2个窗口。控制台和带有浏览器窗口的窗体。
namespace CodeSnippet
{
public partial class browserwindow : Form
{
public browserwindow()
{
InitializeComponent();
//for the browser form to open, the console HAS to run in a seperate thread
Thread ConsoleThread = new Thread(new ThreadStart(TheConsole));
ConsoleThread.Start();
}
public static void TheConsole()
{
while(true)
{
//read the input
string rawinput = Console.ReadLine();
string input = rawinput.ToLower();
//look for commands
if(input == "website")
{
Console.WriteLine("Waiting...");
string website = Console.ReadLine();
//TheBrowser is the name of the browser window
TheBrowser.Navigate(website);
Console.WriteLine("done!");
}
}
}
“TheBrowser.Navigate”在这段代码中不起作用。 但是,如果我删除“TheConsole()”上的“静态”,则代码完全正常。
现在我的问题是:从函数中删除静态是否“没问题”?
答案 0 :(得分:1)
static意味着你从类中调用它,所以browserwindow.Navigate();
会编译。非静态意味着必须从类的实例调用它,因此TheBrowserWindow.Navigate();
在方法不是静态时成功编译。这意味着您要告诉该特定实例调用其Navigate方法。
非静态方法对调用它的特定实例具有特殊访问权限,因此可以说this.x
访问该实例的变量x,或this
来引用实例本身。
你还没有发布方法Navigate
的功能,但听起来它非常适合非静态,因为它听起来像是在告诉浏览器对象的特定实例导航到页面。所以你把它变成非静态的可能更好。但是,如果您发布该方法的代码,您可以得到更好的答案。