2016-03-14 25 views
0

接口:在C#中 「這個」 關鍵詞

public interface ISubject 
{ 
    void registerObserver(IObserver o); 
    void removeObserver(IObserver o); 
    void noifyObservers(); 
} 

public interface IObserver 
{ 
    void update(float temp, float humidity, float pressure); 
} 

這裏是類

public class CurrentConditionsDisplay : IObserver 
    public float temperature; 
    public float humidity; 
    public ISubject weatherData; 

    public CurrentConditionsDisplay(ISubject weatherData) 
    { 
     this.weatherData = weatherData; 
     weatherData.registerObserver(this); 
    } 
} 

registerObserver函數的參數是IObserver但在構造函數中使用:

weatherData.registerObserver(this); 

「this」是什麼意思?我知道「this」關鍵字指的是類的當前實例,但在這種情況下,「this」關鍵字的含義是什麼?

+4

完全一樣。您將'this'作爲參數傳遞給'registerObserver'方法。 –

+2

這裏是正在執行構造函數的CurrentConditionsDisplay實例。 – Adil

+1

「CurrentConditionsDisplay」由其構造函數實例化,該構造函數也將其自身傳遞給'weatherData.registerObserver'方法。您可以在該方法中傳遞'CurrentConditionsDisplay',因爲它實現了'IObserver'接口。 – navigator

回答

0

發帖作爲答案也:

CurrentConditionsDisplay由它的構造,其也通過自身到weatherData.registerObserver方法實例化。您可以在該方法中通過CurrentConditionsDisplay,因爲它實現了IObserver接口。

1

CurrentConditionsDisplay類實現IObserver,它將它自己的構造函數中的this關鍵字傳遞給weatherData.registerObserver,它依賴於實現IObserver的對象實例。

它也可以是一個dependency的模式將此對象注入到weatherData對象中,該對象在其創建時等待IObserver的實例。