您可以在非靜態的類上定義靜態方法。
例如:
static void Main()
{
Foo foo = new Foo();
Foo.DoSomething();
foo.DoSomethingElse();
}
public class Foo
{
public static void DoSomething()
{
Console.WriteLine("DoSomething");
}
public void DoSomethingElse()
{
Console.WriteLine("DoSomethingElse");
}
}
但不會是一個更好的解決方案,以通過MainWindow
作爲參數到用戶控制?所以用戶控件知道它屬於哪個窗口並且可以訪問它的一個功能? (甚至可以更好地爲此聲明一個接口並傳遞接口)。
這看起來像:
public interface IWindow
{
string SomeWindowActivity();
}
public class MyUserControl
{
public IWindow Window { get; set; }
public void SomeActionOnUserControl()
{
string data = Window.SomeWindowActivity();
}
}
public class MainWindow : IWindow
{
MyUserControl MyUserControl { get; set; }
public MainWindow()
{
// Link the UserControl to the Window it's one. This can be done trough the
// constructor or a property
MyUserControl.Window = this;
}
public string SomeWindowActivity()
{
// Some code...
return "result";
}
}
但該代碼將無法正常工作,因爲我無法使我的主窗口的實例,因爲StackOverFlow,所以必須有另一種選擇:) – Letoir 2011-12-19 08:49:04
如果你的方法是因爲它使用MainWindow的字段,所以你必須創建一個實例。如果你的方法不使用MainWindow的字段或參數或...,爲什麼不使它成爲靜態的? – 2011-12-19 08:51:33
@Martin因爲當我使它靜態它不會工作,它給了我一個錯誤,對非靜態字段,方法或屬性的abject引用是必需的? – Letoir 2011-12-19 08:52:06