class A实现IC
class B工具IC
class Factory有方法GetObject(int x); x=0因为A,x=1为B.
我如何可以强制的使用Factory.GetObject方法来创建类型的对象A,并B防止类似new A(),这应该是Factory.GetObject(0)?
Dar*_*rov 10
如何强制使用Factory GetObject方法创建类型A和B的对象并阻止类似新的A()
您不能强制使用Factory.GetObject,在内部标记A和B构造函数之后,您应该在您提供的API文档中编写这些内容.
public class A: IC
{
internal A() { }
}
public class B: IC
{
internal B() { }
}
public static class Factory
{
public static IC GetObject(int x)
{
if (x == 0)
{
return new A();
}
if (x == 1)
{
return new B();
}
throw new ArgumentException("x must be 1 or 2", "x");
}
}
Run Code Online (Sandbox Code Playgroud)
这样,将无法从其他程序集访问这些构造函数.另外,不要忘记Reflection,它允许直接实例化这些类,无论你多么努力地隐藏它们.
| 归档时间: |
|
| 查看次数: |
2857 次 |
| 最近记录: |