使用interface调用2个方法

时间:2015-05-28 18:02:20

标签: interface abstract

我想声明一个从中继承过它的接口 会自动做2次操作 1 - 将写入功能开始的日志
2 - 将写入功能结束的日志 这些行动将自动完成 程序员唯一应该做的就是在接口上实现decared函数 有些人对如何实施它有任何想法?

1 个答案:

答案 0 :(得分:0)

您无法使用接口执行此操作,但是您可以提供包含其他实现的接口的实现并自行记录函数调用。例如:

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");
相关问题