扩展方法 - 如何在继承中返回正确的类型?

时间:2013-04-11 14:50:12

标签: c# extension-methods

我正在尝试从我的Repository类创建泛型方法。这个想法是一个做某事的方法,并返回调用它的类的实例。

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实例。任何的想法?非常感谢你!!!

2 个答案:

答案 0 :(得分:6)

您可以尝试使用泛型

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

答案 1 :(得分: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
相关问题