2010-10-30 79 views
0

考慮這個例子:重載一個抽象方法

public interface IAccount 
{ 
    string GetAccountName(string id); 
} 

public class BasicAccount : IAccount 
{ 
    public string GetAccountName(string id) 
    { 
     throw new NotImplementedException(); 
    } 

} 

public class PremiumAccount : IAccount 
{ 
    public string GetAccountName(string id) 
    { 
     throw new NotImplementedException(); 
    } 

    public string GetAccountName(string id, string name) 
    { 
     throw new NotImplementedException(); 
    } 
} 

protected void Page_Load(object sender, EventArgs e) 
{ 

    IAccount a = new PremiumAccount(); 

    a.GetAccountName("X1234", "John"); //Error 
} 

我怎樣才能調用從客戶端重寫的方法,而不必抽象/接口上定義一個新的方法簽名(因爲它僅僅是一個特殊的高級賬戶的情況)?我在這個設計中使用抽象工廠模式...謝謝...

回答

1

那麼,考慮到它只是爲PremiumAccount類型定義的,你知道你可以稱之爲的唯一方法是,如果a實際上是PremiumAccount,對吧?所以轉換爲PremiumAccount第一:

IAccount a = new PremiumAccount(); 

PremiumAccount pa = a as PremiumAccount; 
if (pa != null) 
{ 
    pa.GetAccountName("X1234", "John"); 
} 
else 
{ 
    // You decide what to do here. 
} 
2

您將不得不將接口轉換爲特定的類。請記住,這會將接口的整個概念從窗口中移出,並且在所有情況下都可以使用特定的類。改爲考慮調整你的架構。

+0

是的,正如我所說,這只是特殊情況,因爲抽象圖案有特殊的情況下,像這樣沒有具體的解決方案... – CSharpNoob 2010-10-30 16:45:32

2

你投的參考特定類型:

((PremiumAccount)a).GetAccountName("X1234", "John"); 
+0

'IAccount一個=新PremiumAccount();'所以沒有必要cast – 2010-10-30 17:15:52

+0

@SaeedAlg:你錯了。該引用是「IAccount」類型的,因此它不知道只存在於「PremiumAccount」中的方法。 – Guffa 2010-10-30 17:25:48

+0

對不起的方法名稱是一樣的:D – 2010-10-30 17:41:57

2

您可以定義IPremiumAccount接口,這兩種方法並實現它的PremiumAccount類。檢查一個對象是否實現接口可能比檢查特定的基類更好。

public interface IPremiumAccount : IAccount 
{ 
    public string GetAccountName(string id, string name); 
} 

public class PremiumAccount : IPremiumAccount 
{ 

// ... 

IAccount a = factory.GetAccount(); 
IPremiumAccount pa = a as IPremiumAccount; 
if (pa != null) 
    pa.GetAccountName("X1234", "John");