C# 如何使用两个名称相同但签名不同的方法创建通用接口?
我在尝试创建一个通用接口时收到此错误,该接口有两个名称相同但签名不同的方法。 你知道我做错了什么以及如何修复吗 类型“XXX.Interfaces.IRepository”已使用相同的参数类型定义了名为“Delete”的成员C# 如何使用两个名称相同但签名不同的方法创建通用接口?,c#,.net,C#,.net,我在尝试创建一个通用接口时收到此错误,该接口有两个名称相同但签名不同的方法。 你知道我做错了什么以及如何修复吗 类型“XXX.Interfaces.IRepository”已使用相同的参数类型定义了名为“Delete”的成员 公共接口IRepository:IRepositoryReadOnly { 无效添加(T实体); 无效更新(T实体); 无效删除(T id); 无效删除(T实体); 作废保存(); } 您的方法没有不同的签名。方法参数的名称无关紧要,只有类型 如何在调用代码中指定要调用的方
公共接口IRepository:IRepositoryReadOnly
{
无效添加(T实体);
无效更新(T实体);
无效删除(T id);
无效删除(T实体);
作废保存();
}
您的方法没有不同的签名。方法参数的名称无关紧要,只有类型
如何在调用代码中指定要调用的方法
您的id
也是T
类型,还是应该是int
类型
public interface IRepository<T> : IRepositoryReadOnly<T> {
void Add(T entity);
void Update(T entity);
void Delete(int id);
void Delete(T entity);
void Save();
}
公共接口IRepository:IRepositoryReadOnly{
无效添加(T实体);
无效更新(T实体);
无效删除(int-id);
无效删除(T实体);
作废保存();
}
参数名称不计入签名
如果我调用了repository.Delete(5)
,您如何知道要运行哪个方法
您可能需要重命名它们。例如,DeleteById(T-id)
和DeleteEntity(T-entity)
您有两个具有相同签名的方法(Delete)。您应该删除其中一个。您可能需要
public interface IRepository<T> : IRepositoryReadOnly<T>
{
void Add(T entity);
void Update(T entity);
void Delete(object id);
void Delete(T entity);
void Save();
}
公共接口IRepository:IRepositoryReadOnly
{
无效添加(T实体);
无效更新(T实体);
作废删除(对象id);
无效删除(T实体);
作废保存();
}
为什么要传递一个T以按ID删除?T将是实体类型您可能必须引入另一个类型参数作为
逆变
,以将其反映为不同的签名,例如X
public interface IRepository<T, in X> : IRepositoryReadOnly<T>
{
void Add(T entity);
void Update(T entity);
void Delete(X id);
void Delete(T entity);
void Save();
}
公共接口IRepository:IRepositoryReadOnly
{
无效添加(T实体);
无效更新(T实体);
无效删除(X id);
无效删除(T实体);
作废保存();
}
方法的签名由方法的名称和
其每种形式的类型和种类(值、引用或输出)
参数,按从左到右的顺序考虑
抄袭自
因此,您的Delete(T)
方法对这两种方法具有相同的签名。您可以将您的签名更改为此(或将id
放为int
/long
):
它们具有相同的签名(重要的是参数类型,而不是参数名称) 如果您的所有实体都有一个ID标识字段,则可能需要将其中一个删除方法更改为
void Delete(int id);//or another type, if that's a GUID, a string...
但是,为了能够在“通用环境”中实现delete函数,您可能需要让所有实体实现一个接口(如果您不想编写太多代码,它们可能继承自实现该接口的公共抽象基类)
如果您有一个带有公共和/或抽象和/或虚拟方法的基本存储库抽象类(假设您不想为所有实体绝对实现Delete(int-id)
,那么您可能需要这样做)
并添加一个约束
public interface IRepository<T> : IRepositoryReadOnly<T> where T : class, IHasId
公共接口IRepository:IRepositoryReadOnly,其中T:class,IHasId
试试这个:
public interface IRepository<T> : IRepositoryReadOnly<T>
{
void Add(T entity);
void Update(T entity);
void Delete(T id);
void Delete(T entity) where T : <EntityType>;
void Save();
}
公共接口IRepository:IRepositoryReadOnly
{
无效添加(T实体);
无效更新(T实体);
无效删除(T id);
作废删除(T实体),其中T:;
作废保存();
}
删除方法的签名相同。它们都是无效的,并且它们以一个相同类型的对象T作为论点。你遗漏了什么吗?
public interface IHasId {
int Id {get;set;}
}
public interface IRepository<T> : IRepositoryReadOnly<T> where T : class, IHasId
public interface IRepository<T> : IRepositoryReadOnly<T>
{
void Add(T entity);
void Update(T entity);
void Delete(T id);
void Delete(T entity) where T : <EntityType>;
void Save();
}