2013-04-11 52 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