0
我想聲明的是誰以往任何時候都繼承它的接口 會自動完成2操作 1將寫入日誌的功能開始
2將寫入日誌的功能結束 這些動作將自動完成 程序員應該做的唯一事情就是實現界面上的功能decely 有些人有任何想法應該如何實現它?使用接口調用2種方法
我想聲明的是誰以往任何時候都繼承它的接口 會自動完成2操作 1將寫入日誌的功能開始
2將寫入日誌的功能結束 這些動作將自動完成 程序員應該做的唯一事情就是實現界面上的功能decely 有些人有任何想法應該如何實現它?使用接口調用2種方法
你不能用接口來做到這一點,但是你可以提供一個接口實現來包裝另一個實現並自己記錄函數調用。例如:
public interface IExample
{
void DoSomething(string parameter1);
}
public class ExampleImpl : IExample
{
private IExample actualImplementation;
public ExampleImpl(IExample actualImplementation)
{
this.actualImplementation = actualImplementation;
}
public void DoSomething(string parameter1)
{
//Code to log function begin here
this.actualImplementation.DoSomething(parameter1);
//Code to log function end here
}
}
現在假設另一個程序員實現接口以及爲例子起見,假設它們的實現被稱爲AnotherProgrammersImplementation
IExample thisObjectLogsFunctionCalls = new ExampleImpl(new AnotherProgrammersImplementation());
thisObjectLogsFunctionCalls.DoSomething("test string");
您好感謝您的快速反應,現在我需要繼承ExampleImpl? instaniate我的新對象,並調用新的方法DoSomething?我想只從IExample繼承我明白它可以通過使用batract類和接口任何想法來完成? – user1092626
如果您從ExampleImpl繼承,那麼將不會重寫日誌記錄功能,而是從IExample繼承,然後如上所示用ExampleImpl包裝它。 – DanL