2017-04-04 54 views
0

我有這個代碼。問題是我需要從類Database訪問類MainWindow。我嘗試從MainWindow繼承Database,但它沒有奏效。我只需要在兩門課都有參考。 感謝您的任何建議!兩個類之間的引用

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

嘗試傳遞MainWindow作爲Database類的構造函數參數 – Marusyk

+5

**不要這樣做。**這會打破SoS(分離問題)和封裝(*保留私有類private *)。您的數據庫類應該完成它的工作並返回結果。然後,您的MainWindow類應該更新它自己的標籤。不要在課堂上分享私人狀態。 – Igor

+0

只要數據庫在其構造函數中使用MainWindow類型的對象,並將其傳遞給專用字段即可。用你有的任何其他參數傳入「this」。然後你可以在數據庫中訪問它。最好使用接口對象,以免與實際的MainWindow綁定。 @Igor在這種情況下是正確的,但是,這純粹是如何做到這一點 - 不是你應該在這裏... –

回答

1

有幾個方法可以做到這一點...

  • 傳入數據庫的構造主窗口的到數據庫的引用。這是不推薦的,因爲數據庫依賴於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"; 
    } 
} 

傳遞構造行動...

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