我有这个代码。问题是我需要从班级Database
访问班级MainWindow
。我试图从Database
继承MainWindow
,但它没有用。我只需要在两个类中引用其他类。
谢谢你的建议!
public partial class MainWindow : Window
{
Database db = new Database(@"database.txt");
public MainWindow()
{
InitializeComponent();
}
public void setLabel(string s)
{
Vystup.Content = s;
}
}
class Database
{
//constructor and other methods
public void doSomething()
{
//Here I want to set Label in MainWindow, something like
//MainWindow.setLabel("hello");
}
}
答案 0 :(得分:1)
有几种方法可以做到这一点......
传递参考(不推荐)......
public partial class MainWindow : Window {
Database db = new Database(this, @"database.txt");
public void setLabel(string s) {
Vystup.Content = s;
}
}
class Database {
private MainWindow _mainWindow { get; set; }
public Database(MainWindow window, string file) {
this._mainWindow = window;
...
}
public void doSomething() {
_mainWindow.setLabel("hello");
}
}
数据库返回要设置的值...
public partial class MainWindow : Window {
Database db = new Database(@"database.txt");
public void setLabel(string s) {
Vystup.Content = s;
}
public void SomeDatabaseThing()
{
string returnValue = db.doSomething();
setLabel(returnValue);
}
}
class Database {
public Database(string file) {
...
}
public string doSomething() {
return "hello";
}
}
在构造函数中传递Action ...
public partial class MainWindow : Window {
Database db = new Database(@"database.txt", setLabel);
public void setLabel(string s) {
Vystup.Content = s;
}
}
class Database {
private Action<string> _onDoSomething = null
public Database(string file, Action<string> onDoSomething) {
this._onDoSomething = onDoSomething;
...
}
public void doSomething() {
onDoSomething("hello");
}
}