Hou*_*ell 1 c# oop class-design class
我正在建立一个库,我有一个类似如下的模式:
public class Foo : Foo_Impl
{
}
public class Foo_Impl
{
}
Run Code Online (Sandbox Code Playgroud)
我不希望其他开发人员意外地使用Foo_Impl类.有什么选择可以隐藏这个?我也想把它隐藏在它定义的同一个程序集中的其他类中.理想情况下,我喜欢这样做:
public class Foo : Foo_Impl
{
private class Foo_Impl
{
}
}
Run Code Online (Sandbox Code Playgroud)
但这并不是出于各种原因.
我还没有看到这个建议,所以我想我会添加我的$ .02.
如何使用组合而不是继承?Foo_Impl的一个实例可以由Foo维护,并且永远不会对外界可见(因为Foo_impl对于程序集是私有的).可以根据需要通过接口将调用传递给Foo_Impl函数.您获得了相同的功能,没有任何设计问题.
private class Foo_Impl
{
public void DoSomething() { }
}
public class Foo
{
private Foo_Impl _implementation;
public Foo() { _implementation = new Foo_Impl(); }
public void DoSomething() { _implementation.DoSomething(); }
}
Run Code Online (Sandbox Code Playgroud)
至于"将它隐藏在程序集中的其他类"中,如果你真的觉得这是合适的,你可以把它变成一个嵌套类.
做Foo_Impl一个抽象课.这不会阻止其他开发人员从中获取,但它将无法Foo_Impl直接创建实例- 它需要通过创建派生对象来实例化,例如Foo.
public abstract class Foo_Impl
{
public Foo_Impl()
{
}
}
public class Foo : Foo_Impl
{
public Foo() // implicitly calls the base class's constructor
{
}
}
Run Code Online (Sandbox Code Playgroud)
-
var works = new Foo(); // Works
var error = new Foo_Impl(); // Compiler error
Run Code Online (Sandbox Code Playgroud)
根据Thomas Levesque的建议,您还可以选择将抽象构造函数设置为内部:
public abstract class Foo_Impl
{
internal Foo_Impl()
{
}
}
public class Foo : Foo_Impl
{
public Foo() // implicitly calls the base class's constructor
{
}
}
Run Code Online (Sandbox Code Playgroud)
这将阻止开发人员从Foo_Impl程序集外部继承.