對於全部實現相同接口的一組類,假定一個或多個類具有不屬於接口定義的其他方法。當我創建這些對象時,使用接口是否有訪問這些方法的方法?還是我必須創建每個單獨的對象而不使用接口?如何訪問不屬於接口定義的方法? (同時仍然對接口進行編程)
class Program
{
static void Main(string[] args)
{
ITextProcessor processor = new FileProcessor();
string result = processor.ReadText();
processor.SaveText(result);
ITextProcessor processorTest = new FileProcessorTest();
processorTest.testMethod() // unavailable
}
}
class FileProcessor : ITextProcessor
{
public string ReadText()
{
// read in text from a
// file and return it
return Console.ReadLine();
}
public void SaveText(string processedText)
{
// write processedText out to file.
Console.WriteLine(processedText);
}
}
class FileProcessorTest : ITextProcessor
{
public string ReadText()
{
// read in text from a
// file and return it
return Console.ReadLine();
}
public void SaveText(string processedText)
{
// write processedText out to file.
Console.WriteLine(processedText);
}
public void testMethod()
{
//I want to be able to access this method
}
}
interface ITextProcessor
{
string ReadText();
void SaveText(string processedText);
}
您必須創建具體的實現對象而不是接口,或者將接口實例轉換爲該實現對象(並檢查當然不能如此投射的實例)。無論哪種情況,您都已經打破了界面提供的抽象。這聽起來像你需要重新思考你的抽象,而不是試圖繞過它們。 – David
閱讀Liskov的Substition原理 - 它破壞了接口的全部觀點,以檢查具體類的未定義在接口上的任意方法。如果你發現自己這樣做了,你可能需要重新審視你的設計。 –
那麼,如果物體都非常相似,但它們之間的差異很小,那麼最好的解決方案是什麼?使他們有資格使用通用界面,但有變化。 – erotavlas