2009-08-24 51 views
2

此时,我为我的“员工”类拥有这段代码。但对于“客户”和其他所有人来说,我几乎是一样的。类,接口,泛型....需要简化

有没有一种方法来创建我的课“EmployeeRepository”,但更多的东西像这样MyRepo <员工>等价,但在这种情况下实施IEmployeeRepository,ICustomerRepository如果我这样做MyRepo <客户>。当然,get方法返回的员工,客户或其他...

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

是的,像斯宾塞Ruport已经提到,收集你的代码在一个接口或抽象基类和我一样:

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; 
    } 
} 
+0

需要的接口,我使用IoC – 2009-08-24 06:41:03

+0

我无法编辑,但是有一些语法错误代码,如果你能纠正。但是,这是工作。再次感谢 – 2009-08-24 08:25:31

1

你可以 - 除非你会使IEmployeeRepository接口通用一样,所以你会:

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

} 

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

} 

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

希望帮助:)

+0

是在有可能的“公共接口IRepository :IRepositoryActionActor ”的方法添加到根据T值执行? – 2009-08-24 06:54:28

1

在这个时候,我有这块 代码为我的“雇员”类。但是我的 对于“顾客” 和所有其他人几乎一样。

找出它们有什么共同之处,并为该组数据命名并为其创建接口。我的猜测是IPerson可能会工作。

然后,您可以创建一个get person存储库,该存储库返回一个IPerson对象,并且可以是Employee或Customer。

+0

IRepositoryActionActor对所有(Employee,Customer,...)都是通用的,但是IEmployeeRepository(ICustomerRepository,...)添加一些特定的声明 – 2009-08-24 06:37:10