我有一個通用的接口:作爲如何定義泛型類的擴展方法?
public IRepository<T>
{
void Add(T entity);
}
和類:
public class Repository<T>:IRepository<T>
{
void Add(T entity)
{ //Some Implementation
}
}
現在我想作出上述接口的擴展方法。我做了以下類:
public static class RepositoryExtension
{
public static void Add(this IRepository<T> dataAccessRepository, T entity, string additionalValue)
{
//Some Implementation
}
}
但我在擴展名添加方法中出現錯誤。它不能識別我傳遞給IRepository的類型'T'。我無法事件將此Type傳遞給我的Extenstion Methods類,即RepositoryExtension < T>。請指導適當的方式。
但在這種情況下,每當我調用這個擴展方法時,我都會傳遞這個類型。現在我這樣做: IRepository < Employee > employeRepository = new Repository < Employee >(); employeeRepository.Add(entity); 但在這種情況下,您建議我將類型傳遞給擴展方法,如下所示:employeeRepository < Employee >(entity,「someValue」); – 2010-09-20 07:29:55
你試過了嗎? C#和.Net會根據IRepository的類型找出類型 – Rohith 2010-09-20 07:36:16
是的,我試過了,它工作。非常感謝Rohith的幫助。我正在做同樣的事情,但我在調用方法時也通過了Type。我試過了,沒有通過Type'T'和.Net算出:)非常感謝 – 2010-09-20 07:43:28