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

后端 未结 10 1213
小鲜肉
小鲜肉 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条回答
  •  萌比男神i
    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.

提交回复
热议问题