What are some advantages to using an interface in C#?

后端 未结 10 1185
小鲜肉
小鲜肉 2020-12-04 18:16

I was forced into a software project at work a few years ago, and was forced to learn C# quickly. My programming background is weak (Classic ASP).

I\'ve learned qui

相关标签:
10条回答
  • 2020-12-04 18:46

    Simple answer based on first principles:

    A program is a universe with its own metaphysics (the reality/substance/stuff of the code) and epistemology (what you can know/believe/reason about the code). A good programming language tries to maximize the metaphysical flexibility (lets you make the stuff easily) while ensuring epistemic rigor (makes sure your universe is internally consistent).

    So, think of implementation inheritance as a metaphysical building block (the stuff that makes up your little universe of code) and interface inheritance as an epistemic constraint (it allows you to believe something about your code).

    You use interfaces when you only want to ensure that you can believe something. Most of the time that's all you need.

    0 讨论(0)
  • 2020-12-04 18:48

    One Simple Answer: Use interfaces to program against the contract rather than the implementation.

    How could that possibly help? Starting to use interfaces will (hopefully) get you in the habit of coupling classes more loosely. When you code against your own concrete classes, it's easy to start poking the data structures without a strict separation of concerns. You end up with classes which "know" everything about the other classes and things can get pretty tangled. By limiting yourself to an interface, you only have the assurance that it fulfills the interface's contract. It injects a sometimes helpful friction against tight coupling.

    0 讨论(0)
  • 2020-12-04 18:49

    Here is a book that talks all about interfaces. It promotes the notion that interfaces belong to the client, that is to say the caller. It's a nice notion. If you only need the thing that you're calling to implement - say - count() and get(), then you can define such an interface and let classes implement those functions. Some classes will have many other functions, but you're only interested in those two - so you need to know less about the classes you're working with. As long as they satisfy the contract, you can use them.

    0 讨论(0)
  • 2020-12-04 18:53

    IOC and Dependency injection have already been mentioned above, and I would urge you to look at them.

    Largely, however, interfaces allow a contract to be specified for an object that doesn't require an inheritance model.

    Lets say I have class Foo, that has functions x and y and property z, and I build my code around it.

    If I discover a better way to do Foo, or another sort of Foo requires implementation, I can, of course, extend a base Foo class to FooA, FooB, MyFoo etc, however that would require that all Foos have the same core functionality, or, indeed that any future Foo creators have access to the base Foo class and understand its internal workings. In C#, that would mean future Foos could not inherit from anything else but Foo, as C# does not support multiple inheritance.

    It would also require me to be aware of possible future states of Foo, and try not to inhibit them in my base Foo class.

    Using an interface IFoo simply states the 'contract' that a class requires to work in my Foo framework, and I don't care what any future Foo classes may inherit from or look like internally, as long as they have fn x fn y and z. It makes a framework much more flexible and open to future additions.

    If, however, Foo requires a large amount of core at its base to work that would not be applicable in a contract scenario, that is when you would favour inheritance.

    0 讨论(0)
  • 2020-12-04 18:54

    An example. Consider an MDI application that shows reports, there's basically 2 different report types. A chart, and a grid. I need to Save these reports as PDF and I need to mail them to someone. The event handler for the menu the user clicks to save a report to PDF could do this:

    void ExportPDF_Clicked(...) {
       if(currentDocument is ChartReport) {
          ChartReport r = currentDocument as ChartReport;
          r.SavePDF();
       } else if(currentDocument is GridReport) {
         GridReport r = currentDocument as GridReport;
          r.SavePDF();
       }
    }
    

    I'll rather make my ChartReport and GridReport implement this interface:

    public interface Report {
      void MailTo();
      void SavePDF();
    }
    

    Now I can do:

    void ExportPDF_Clicked(...) {
       Report r = currentDocument as Report;
       r.SavePDF();
    }
    

    Similar for other code that need to do the same operation(save it to a file,zoom in,print,etc.) on the different report types. The above code will still work fine when I add a PivotTableReport also impelmenting Rpoert the next week.

    0 讨论(0)
  • 2020-12-04 18:54

    You mentioned having difficulty finding a practical use for interfaces.. I've found that they come into their own when building extensible applications, for example a plugin-based app where a third-party plugin must conform to specific rules.. These rules can be defined by an interface.

    You could make it so that when the plugin is loaded, it must have an Init method that takes a class that implements IServices interface.

    public interface IServices
    {
        DataManager Data { get; set; }
        LogManager Log { get; set; }
        SomeOtherManager SomeOther { get; set; }
    }
    
    public class MrPlugin
    {
        public void Init(IServices services)
        {
            // Do stuff with services
        }
    }
    

    So.. If you have a class that implements the IServices interface, and then you instantiate it once, you can pass it to all the plugins upon initialisation and they can use whatever services you have defined in the interface.

    0 讨论(0)
提交回复
热议问题