Using Interface variables

后端 未结 12 1138
广开言路
广开言路 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 05:38

    The purpose of the Interface is to define a contract between several objects, independent of specific implementation.

    So you would usually use it when you have an Intrace ISomething, and a specific implementation

    class Something : ISomething
    

    So the Interface varialbe would come to use when you instantiate a contract:

    ISomething myObj = new Something();
    myObj.SomeFunc();
    

    You should also read interface C#

    Update:

    I will explaing the logic of using an Interface for the variable and not the class itself by a (real life) example:

    I have a generic repositor interace:

    Interface IRepository {
        void Create();
        void Update();
    }
    

    And i have 2 seperate implementations:

    class RepositoryFile : interface IRepository {}
    class RepositoryDB : interface IRepository {}
    

    Each class has an entirely different internal implementation.

    Now i have another object, a Logger, that uses an already instansiated repository to do his writing. This object, doesn't care how the Repository is implemented, so he just implements:

    void WriteLog(string Log, IRepository oRep);
    

    BTW, this can also be implemented by using standard classes inheritance. But the difference between using interfaces and classes inheritance is another discussion.

    For a slightly more details discussion on the difference between abstract classes and interfaces see here.

提交回复
热议问题