Class, Interface, Generics .... simplification required

At this time, I have this piece of code for my employee class. But I have pretty much the same for the "client" and everyone else.

Is there a way to create an equivalent to my "EmployeeRepository" class, but more like this MyRepo <Employee> but implement IEmployeeRepository in this case, ICustomerRepository, if I make it MyRepo <Customer>. Of course the get method returns Employee, Customer or something else ...

public class EmployeeRepository : NHRepository<Employee>, IEmployeeRepository
{
    public Employee Get(Guid EmployeeId)
    {
        return base.Get(EmployeeId);
    }
}

public interface IEmployeeRepository : IRepositoryActionActor<Employee>
{

}

public interface IRepositoryActionActor<T>
{
    T Get(Guid objId);
}

      

+2


source to share


3 answers


Yes, as Spencer Ruport already mentioned, compile your code in an interface or abstract base class like I did:



public interface IPerson
{
    void DoSomething( );
}

public abstract class Person : IPerson
{

    public virtual void DoSomething( )
    {
        throw new NotImplementedException( );
    }
}

public class Employee : Person
{
    public override void DoSomething( )
    {
        base.DoSomething( );
        /* Put additional code here */
    }
}

public class Customer : Person { }

public class PersonRepository<T> : System.Collections.Generic.List<T> where T : IPerson, new( )
{
    public T Get( Guid id )
    {
        IPerson person = new T( );
        return (T)person;
    }
}

      

+2


source


You can - except that you also create the IEmployeeRepository interface, so you will have:

public class MyRepo<U> : NHRepository<U>, IRepository<U>
{
...

}

public interface IRepository<T> : IRepositoryActionActor<T>
{

}

public interface IRepositoryActionActor<T>
{
    T Get(Guid objId);
}

      



Hope that helps :)

+1


source


At this time I have this piece of code for my employee class. But I have pretty much the same for "client" and everyone else.

Find out what they have in common and provide a name for this dataset and create an interface for it. My guess is that IPerson will probably work.

Then you can create a get person repository that returns an IPerson object and can be either an Employee or a Client.

+1


source







All Articles