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

Kiw*_*nax 3 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");
Run Code Online (Sandbox Code Playgroud)

好吧,这样我就可以得到BaseRepository实例.但我需要获取调用此方法的FooRepository和BarRepository实例.任何的想法?非常感谢!!!

ale*_*lex 6

您可以尝试使用泛型

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

  • +1,但我们可以通过使用`where T:BaseRepository`来改进这一点 (2认同)
  • @Kiwanax,你不需要在`<>`中指定类型,它将被编译器驱使.你的代码看起来像`fooRepository.AddParameter("value")` (2认同)