类内的C#-接口
根据MSDN,文档接口可以是类或命名空间的成员: 例如,我可以声明:类内的C#-接口,c#,C#,根据MSDN,文档接口可以是类或命名空间的成员: 例如,我可以声明: public class Test { public interface IMemberofTest { void get(); } } 在类中拥有接口有什么用?它不会破坏实际接口使用的目的吗?如果出于某种原因,该接口仅在该类的上下文中才有意义,并且您希望通过这样实现它来明确这一点,则不会 我必须说,为了它的价值,我从未使用过这个构造。这个类是另一个名称空间。 因此,该接口可用于在类中
public class Test
{
public interface IMemberofTest
{
void get();
}
}
在类中拥有接口有什么用?它不会破坏实际接口使用的目的吗?如果出于某种原因,该接口仅在该类的上下文中才有意义,并且您希望通过这样实现它来明确这一点,则不会
我必须说,为了它的价值,我从未使用过这个构造。这个类是另一个名称空间。
因此,该接口可用于在类中方法之间流动的数据上强制约定,或仅用于更精确地限定接口的范围。当您想要在类中分解内容时,它们非常有用
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
}
}
就我个人而言,我不喜欢一个代码文件中的许多类——我发现这只会让事情很难找到。在这种情况下,依赖注入不是更好的选择吗?这样,您就可以让调用Print的人决定打印方式(只要实现了IPrinter),从而降低发票的复杂性,同时允许使用比HTML和PDF更多类型的打印机(例如模拟)。