2009-08-19 79 views
0

下面是我正在做的一個簡單示例。基本上,我有多個接口,可以通過1個類或單獨的類實現,因此我將每個接口存儲在應用程序中。我唯一的問題是關於變量myInterface,yourInterface和ourInterface。 他們引用同一個對象還是有3個不同的對象?在.Net中實現多個接口和對象實例

interface IMyInterface 
{ 
    void MyFunction(); 
} 

interface IYourInterface() 
{ 
    void YourFunction(); 
} 

interface IOurInterface() 
{ 
    void OurFunction(); 
} 

public class MainImplementation : IMyInterface, IYourInterface, IOurInterface 
{ 
    public void MyFunction() { } 
    public void YourFunction() { } 
    public void OurFunction() { } 
} 

private IMyInterface myInterface; 
private IYourInterface yourInterface; 
private IOurInterface ourInterface; 

static void Main(string[] args) 
{ 
    myInterface = new MainImplementation() as IMyInterface; 
    yourInterface = myInterface as IYourInterface; 
    ourInterface = myInterface as IOurInterface; 
} 

獎勵:有沒有更好的方法來做到這一點?

+0

我對這個問題的標題有點困惑。 ByVal或ByRef與提供的代碼示例有什麼關係?沒有任何方法採用任何參數。 – JohnFx 2009-08-19 01:15:43

+0

修正了它。希望,這有點更好。這是一個漫長的一天:) – kevindaub 2009-08-19 01:17:28

回答

5

它們都引用同一個對象。因此對它們的修改形式如下:

ourInterface.X = ... 

將反映在'所有視圖'中。

實際上,你對你的演員所做的事情(我認爲你的意思是你的最後一個是'IOurInterface')給出了一個不同的'視圖'數據。在這種情況下,每個接口都會打開一個函數。

+0

謝謝。我有這樣的感覺,但我只需要驗證。 – kevindaub 2009-08-19 01:21:12

3

它們引用相同的實例。有只有一個實例。

2

1 new = 1 object。他們都參考相同的實例。

0

他們引用同一個對象。將一個對象轉換爲不同的對象會告訴編譯器,當在這個對象上調用一個方法時,使用這個類中定義的方法而不是另一個方法。