两个类之间的引用

时间:2017-04-04 21:06:06

标签: c# wpf

我有这个代码。问题是我需要从班级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");
   }
}

1 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点......

  • 将MainWindow的引用传递给Database的构造函数中的Database。建议不要这样做,因为数据库依赖于MainWindow。
  • 让数据库函数返回MainWindow让数据库执行某些操作时需要设置的值。
  • 在数据库构造函数中传递一个Action,以便在调用doSomething时调用它。

传递参考(不推荐)......

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");
    }
}