2009-08-23 47 views
4

按照MSDN文档界面内可以是一个类或命名空间的成员:C# - 接口类

例如,我可以声明:

public class Test 
{ 
    public interface IMemberofTest 
    { 
     void get(); 
    } 
} 

什么用内部具有接口的一类?它不会破坏真正的界面使用的目的吗?

回答

7

该类是另一个命名空间。 因此,该接口可用于强制在类中的方法之间传递的数据上签订合同,或者仅用于更精确地限定接口范围。

2

如果出于某种原因,该接口仅在该类的上下文中才有意义,并且您希望通过像这样实现它来清除它,则不是这样。

我必须说,我从来没有使用这个构造一次,因为它是值得的。

3

当你想在课堂上分解东西时,它们很有用。

public class Invoice 
    { 
     public String Print(Type type) 
     { 
      IPrinter printer = null; 
      switch (type) 
      { 
       case Type.HTML: 
        printer = new HtmlPrinter(this); 
        break; 
       case Type.PDF: 
        printer = new PdfPrinter(this); 
        break; 
       default: 
        throw new ArgumentException("type"); 
      } 

      printer.StepA(); 
      printer.StepB(); 
      printer.StepC(); 

      return printer.FilePath; 
     } 


     private interface IPrinter 
     { 
      void StepA(); 
      void StepB(); 
      void StepC(); 
      String FilePath { get; } 
     } 

     private class HtmlPrinter : IPrinter 
     { 
      //Lots of code 
     } 

     private class PdfPrinter : IPrinter 
     { 
      //Lots of code 
     } 

     public enum Type 
     { 
      HTML, 
      PDF 
     } 
    } 
+0

个人而言,我不是一个代码文件中许多类的粉丝 - 我发现它只是使事情很难找到。 – Paddy 2009-08-23 09:38:44

+1

在这种情况下,不依赖注入是否更好?通过这种方式,您可以让任何打印者决定打印的方式(只要实施IPrinter),从而降低发票的复杂性,同时允许使用比HTML和PDF更多类型的打印机(例如模拟) 。 – 2009-08-23 09:58:36