Using Interface variables

后端 未结 12 1135
广开言路
广开言路 2020-11-28 05:01

I\'m still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.

What I don\'t understand is when you

12条回答
  •  情话喂你
    2020-11-28 06:02

    I believe everyone is answering the polymorphic reason for using an interface and David Hall touches on partially why you would reference it as an interface instead of the actual object name. Of course, being limited to the interface members etc is helpful but the another answer is dependency injection / instantiation.

    When you engineer your application it is typically cleaner, easier to manage, and more flexible if you do so utilizing dependency injection. It feels backwards at first if you've never done it but when you start backtracking you'll wish you had.

    Dependency injection normally works by allowing a class to instantiate and control the dependencies and you just rely on the interface of the object you need.

    Example:

    Layer the application first. Tier 1 logic, tier 2 interface, tier 3 dependency injection. (Everyone has their own way, this is just for show).

    In the logic layer you reference the interfaces and dependency layer and then finally you create logic based on only the interfaces of foreign objects.

    Here we go:

    public IEmployee GetEmployee(string id)
    {
        IEmployee emp = di.GetInstance>().Where(e => e.Id == id).FirstOrDefault();
    
        emp?.LastAccessTimeStamp = DateTime.Now;
    
        return emp;
    }
    

    Notice above how we use di.GetInstance to get an object from our dependency. Our code in that tier will never know or care about the Employee object. In fact if it changes in other code it will never affect us here. If the interface of IEmployee changes then we may need to make code changes.

    The point is, IEmployee emp = never really knows what the actual object is but does know the interface and how to work with it. With that in mind, this is when you want to use an interface as opposed to an object becase we never know or have access to the object.

    This is summarized.. Hopefully it helps.

提交回复
热议问题