我最近來到了這個兩難問題:假設我想用兩個庫每個人的定義了一個接口,用於消費者和耗材:用C#接口設計問題
#region Library A
// This region represents a library (A) defining some interfaces
/// <summary>
/// Interface to be implemented by any processor of type A
/// </summary>
interface AProcessor
{
void Process(AProcessable a);
}
/// <summary>
/// Interface to be implemented by any object processable by a processor of type A
/// </summary>
interface AProcessable
{
int MyPropertyA { get; set; }
}
#endregion
#region Library B
// This region represents a library (B) defining some other interfaces
/// <summary>
/// Interface to be implemented by any processor of type B
/// </summary>
interface BProcessor
{
void Process(BProcessable a);
}
/// <summary>
/// Interface to be implemented by any object processable by a processor of type B
/// </summary>
interface BProcessable
{
int MyPropertyB { get; set; }
}
#endregion
然後,在我的應用程序,我實現了從每個庫同時實現消費品接口耗材類型:
/// <summary>
/// A type processable by processors of type A and processors of type B.
/// </summary>
class Processable :
AProcessable,
BProcessable
{
// Implements interface AProcessable
public int MyPropertyA { get; set; }
// Implements interface BProcessable
public int MyPropertyB { get; set; }
}
我能夠實現消費型處理的,它實現AProcessable和BProcessable的對象的消費類型:
/// <summary>
/// A processor that implements an A-type processor and a B-type processor.
/// </summary>
class Processor :
AProcessor,
BProcessor
{
// I thought that Process method would implement AProcessor.Process() and
// BProcessor.Process() as it expects a Processable object as parameter which
// implements AProcessable and BProcessable, but it doesn't.
// Compiler rises an error telling that Processor doesn't implement neither
// AProcessor.Process() nor BProcessor.Process()
/*
public void Process(Processable a)
{
throw new NotImplementedException();
}
*/
// Implementing both methods does not work because it creates ambiguity: when
// we call Processor.Process(p) being "p" a Processable object the compiler
// doesn't know if it has to call Processor.Process(AProcessable) or
// Processor.Process(BProcessable).
/*
public void Process(AProcessable a)
{
throw new NotImplementedException();
}
public void Process(BProcessable a)
{
throw new NotImplementedException();
}
*/
}
¿什麼是我的設計錯誤,什麼是正確的方法?
在此先感謝。
是的,夥計,它發揮了訣竅。 如果我可以保留Process(AProcessable)和Process(BProcessable)是私人的,那將是完美的,但我認爲這是不可能的。 非常感謝。 –
不可能讓它們成爲私人的,因爲正如亞當寫道的,屬於界面的所有東西都必須公開 –