c# - 类、接口(interface)、泛型......需要简化

标签 c# .net generics

此时,我的“employee”类有这段代码。但我对“客户”和所有其他人的看法几乎相同。

有没有办法创建与我的类“EmployeeRepository”等效的类,但更像是 MyRepo 但在本例中实现 IEmployeeRepository,如果我执行此 MyRepo,则实现 ICustomerRepository。当然 get 方法返回 Employee、Customer 或其他...

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);
}

最佳答案

是的,就像 Spencer Ruport 已经提到的那样,像我一样将代码收集在接口(interface)或抽象基类中:

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

关于c# - 类、接口(interface)、泛型......需要简化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1320715/

相关文章:

c# - .Net 5 Web API CORS LocalHost

c# - 405 - 不允许用于访问此页面的 HTTP 动词。 [IIS 8.5] [Windows Server 2012 R2]

.net - ASP.NET Web API 接口(interface) (WSDL)

c# - JSON反序列化。

arrays - 将多维项添加到数组中,然后一次检索所有项

java - 如何使用 JDBI 进行通用插入?

C# Asp.net无法连接到phpmyadmin

C# 比较 native 类型和可空类型(Int32 和 Int32?)

c# - 如何定义通用约束以便我可以使用 ??合并运算符

c# - 如何按嵌套实体的字段排序/排序?