我有2个C#接口,如下所示:
public interface IEvernoteJobListener
{
void CopyS3File(S3Location src, EvernoteLocation des, Action<Exception> complete);
}
public interface ICopyJobListener
{
void CopyS3File(S3Location src, S3Location des, Action<Exception> complete);
}
除了第二个参数外,你可以看到它们几乎相同,这使得实现几乎完全相同。阻止我将它们合并到一个接口的原因是EvernoteLocation和S3Location是结构体,所以我不能让它们从同一个父节点继承,从而消除它们之间的差异,只保留一个接口和一个方法。
有哪些可能的解决方案可以消除界面的重复?
编辑:
实施准则可能有助于澄清问题:
public void CopyS3File (S3Location src, EvernoteLocation des, Action<Exception> complete)
{
reader.ReadS3ToFile(src, (file, readExc) => {
if(readExc != null)
{
complete(readExc);
return;
}
// This is a Evernote writer.
writer.WriteFromFile(file, des, writeExc => {
complete(writeExc);
});
});
}
public void CopyS3File (S3Location src, S3Location des, Action<Exception> complete)
{
reader.ReadS3ToFile(src, (file, readExc) => {
if(readExc != null)
{
complete(readExc);
return;
}
// This is a S3 writer.
writer.WriteFromFile(file, des, writeExc => {
complete(writeExc);
});
});
}
答案 0 :(得分:1)
您可以使界面通用。
public interface IJobListener<TDes>
{
void CopyS3File(S3Location src, TDes des, Action<Exception> complete);
}
但我不知道这对您的实施有何帮助。
答案 1 :(得分:1)
为什么不在两个结构上实现接口并将其用作输入参数?
public struct S3Location : ICanHasInterface
{
//...
}
public struct EvernoteLocation : ICanHasInterface
{
//...
}
public interface ICopyJobListener
{
void CopyS3File(S3Location src, ICanHasInterface des, Action<Exception> complete);
}
答案 2 :(得分:0)
只需使用泛型类型参数:
interface IJobLIstener<T>
{
void CopyS3File(S3Location src, T des, Action<Exception> complete)
}
public interface IEvernoteJobListener: IJobLIstener<EvernoteLocation>
{
}
public interface ICopyJobListener: IJobLIstener<S3Location>
{
}
顺便说一句,
如果S3Location封装了超过2-3个基本类型值,我建议将其class
而不是structure