C # Concrete redefinition of a common class

Here is the general class I'm working with:

 public interface IRepository<T> where T : EntityObject
{
    RepositoryInstructionResult Add(T item);
    RepositoryInstructionResult Update(T item);
    RepositoryInstructionResult Delete(T item);
}
public class Repository<T> : IRepository<T> where T : EntityObject
{

    RepositoryInstructionResult Add(T item)
    { //implementation}
    RepositoryInstructionResult Update(T item);
    { //implementation}
    RepositoryInstructionResult Delete(T item);
    { //implementation}
 }

Now I sometimes distort the behavior of methods on t: a particular type. Is something like the following possible? This particular attempt gives an error (error 5: partial "repository" declarations must have the same type parameter names in the same order).

public class Repository<Bar> //where Bar : EntityObject
{
    RepositoryInstructionResult Add(Bar item)
    { //different implementation to Repository<T>.Add() }
    //other methods inherit from Repository<T>
 }
+5
source share
4 answers
public class BarRepository : Repository<Bar>
{ 
    RepositoryInstructionResult Add(Bar item) 
    { //different implementation to Repository<T>.Add() } 
    //other methods inherit from Repository<T> 
} 
+4
source

Name your class Repository RepositoryBase and create virtual interface methods. implement them in general form inside your RepositoryBase class, but since u marked methods as virtual u will be able to redefine functionality in your derived classes, your code will look something like this.

 public interface IRepository<T> where T : EntityObject
 {
    RepositoryInstructionResult Add(T item);
    RepositoryInstructionResult Update(T item);
    RepositoryInstructionResult Delete(T item);
 }

 public class Repository<T> : IRepository<T> where T : EntityObject
 {
    virtual RepositoryInstructionResult Add(T item)
    { //implementation}
    virtual RepositoryInstructionResult Update(T item);
    { //implementation}
    virtual RepositoryInstructionResult Delete(T item);
    { //implementation}
  }

U - , Bar, Name it BarRepository Repositorybase . u ,

 public class BarRepository : Repositorybase<Bar>
 {
    public override RepositoryInstructionResult Update(Bar item);
    {
       //Call base method if needed
       //Base.Update(item);

       //implement your custom logic here
    }
  }
0

: , , T . :

if (typeof(T) == typeof(Bar)) {
    // your Bar-specific code
}
// ...

, , , -.

, , , .

0

:

public static void DoSomething(this repository<Bar> repo)
{
  //your custom code goes here
}
0

All Articles