2013-04-11 54 views
3

我想從我的存儲庫類創建一個通用的方法。這個想法是一種做一些事情並返回調用它的類的實例的方法。擴展方法 - 如何在繼承中返回正確的類型?

public class BaseRepository { } 

public class FooRepository : BaseRepository { } 

public class BarRepository : BaseRepository { } 

public static class ExtensionRepository 
{ 
    public static BaseRepository AddParameter(this BaseRepository self, string parameterValue) 
    { 
     //... 
     return self; 
    } 
} 

// Calling the test: 
FooRepository fooRepository = new FooRepository(); 
BaseRepository fooWrongInstance = fooRepository.AddParameter("foo"); 

BarRepository barRepository = new BarRepository(); 
BaseRepository barWrongInstance = barRepository.AddParameter("bar"); 

那麼,這樣我就可以得到BaseRepository實例。但我需要獲得調用此方法的FooRepository和BarRepository實例。任何想法?非常感謝!!!

+0

你是否意識到了'class'類型變量只是_reference_對象?將相同參考返回給方法的調用者的目的是什麼?他已經有這個參考。可能有一個正當的理由(這就是爲什麼我問)。增加:在上面的使用示例中,'='符號只是將相同的引用賦予新變量。這不是一個「錯誤的例子」。該方法不會創建新的實例;這是同一個實例。 – 2013-04-11 14:57:39

+0

返回相同引用Jeppe的目的是在一行上實現大量的方法調用。 「錯誤的實例」是一種說法,我希望兒童實例像返回,但不是基類,你知道嗎? – Kiwanax 2013-04-11 15:44:58

+0

現在我明白了。我想,正確的術語是「錯誤的(不需要的)編譯時類型」或「變量的類型」。 – 2013-04-11 16:05:05

回答

6

您可以嘗試使用泛型

public static class ExtensionRepository 
{ 
    public static T AddParameter<T>(this T self, string parameterValue) where T:BaseRepository 
    { 
     //... 
     return self; 
    } 
} 
+2

+1,但我們可以通過使用'where T:BaseRepository' – 2013-04-11 14:53:26

+0

@ Moo-Juice來改善這一點,謝謝,我已經更新了答案。 – alex 2013-04-11 14:54:57

+0

謝謝,亞歷克斯。我已經想過這個解決方案,但我想創建一個優雅的代碼。例如:「fooRepository.AddParameter(」value「)」而不是「fooRepository.AddParameter (」value「)」,你知道嗎? – Kiwanax 2013-04-11 15:47:46

0

爲什麼你要在第一時間返回self?據我所見(不知道你的方法體內有什麼),你不要給self分配一個新的對象。所以這是您返回的調用方已有的實例。

也許你可以把它返回void

public static void AddParameter(this BaseRepository self, string parameterValue) 
{ 
    //... 
} 

用法:

FooRepository fooRepository = new FooRepository(); 
fooRepository.AddParameter("foo"); 
// fooRepository is still fooRepository after the call 


BarRepository barRepository = new BarRepository(); 
barRepository.AddParameter("bar"); 
// barRepository is still barRepository after the call 
+1

返回同一個實例的目的是調用連續的很多方法,你知道嗎?如:「fooRepository.AddParameter(」「)。AddSomeStuff(」「,」「).AddAnotherStuff(」「).List();」。像這樣的東西。 – Kiwanax 2013-04-11 15:45:59

+0

@Kiwanax好的,那麼你可以使用其他答案的解決方案。 – 2013-04-11 15:58:25

+0

是的,@Jeppe,另一個解決方案解決了我的問題。謝謝您的回答! – Kiwanax 2013-04-11 16:16:33