2009-09-30 99 views
4

我从以前的问题,这个代码,但它不是编译:如何解决存储库模式问题这个泛型?

public interface IEntity 
{  
// Common to all Data Objects 
} 
public interface ICustomer : IEntity 
{ 
    // Specific data for a customer 
} 
public interface IRepository<T, TID> : IDisposable where T : IEntity 
{ 
    T Get(TID key); 
    IList<T> GetAll(); 
    void Save (T entity); 
    T Update (T entity); 
    // Common data will be added here 
} 
public class Repository<T, TID> : IRepository 
{ 
    // Implementation of the generic repository 
} 
public interface ICustomerRepository 
{ 
    // Specific operations for the customers repository 
} 
public class CustomerRepository : Repository<ICustomer>, ICustomerRepository 
{ 
    // Implementation of the specific customers repository 
} 

但在这两条线:

1-公共类资源库:IRepository

2-公共类CustomerRepository:存储库,ICustomerRepository

它给我这个错误:使用泛型类型'TestApplication1.IRepository'需要'2'类型参数

你能帮我解决吗?

回答

5

从存储库/ IRepository继承时,因为他们需要采取两种类型的参数,您需要使用两个类型参数。也就是说,当你从IRepository继承时,需要指定是这样的:类型“:

public class Repository<T, TID> : IRepository<T,TID> where T:IEntity 

public class CustomerRepository : Repository<ICustomer,int>,ICustomerRepository 

编辑以在执行Reposistory

+0

ICustomerRepository在他的代码中是非泛型的。 – 2009-09-30 00:23:29

+0

啊,是的,只是注意到,因为我点击Submit ... – JasonTrue 2009-09-30 00:25:24

+0

现在给出这个错误:类型'T'不能用作通用类型或方法'TestApplication1.IRepository '中的类型参数'T'。没有从'T'到'TestApplication1.IEntity'的装箱转换或类型参数转换。 – 2009-09-30 00:41:19

2

当您实现通用接口时,还需要提供通用接口类型规范。这两行更改为:

public class Repository<T, TID> : IRepository<T, TID> 
    where T : IEntity 
{ 
    // ... 

public class CustomerRepository : Repository<ICustomer, int /*TID type*/>, ICustomerRepository 
{ 
    // ... 
+0

现在给这个错误添加类型约束T'不能用作泛型类型或方法'TestApplication1.IRepository '中的类型参数'T'。没有从'T'到'TestApplication1.IEntity'的装箱转换或类型参数转换。 – 2009-09-30 00:37:31

+0

对不起 - 我编辑了我的答案。您必须将T:IEntity的约束放入Repository中。我忘了包括这一点。 – 2009-09-30 01:00:33