我正在一个项目中,该项目要求我仅通过其自己的程序集实例化(“新”)一个类,而无需实例化其他程序集。这可能吗?
我尝试使用抽象,但这意味着我无法在任何地方实例化它。
示例:下面的类在同一项目/程序集中。
public class Banana
{
public Banana()
{
...
}
}
public class Food.
{
public static Banana InstantiateBanana()
{
Banana banana = new Banana();//<=====How can you instantiate it inside the same assembly? I don't want other assemblies to instantiate it.
...
return banana;
}
}
我知道了!
public class Banana
{
private Banana()
{
...
}
public static Banana InstantiateBanana()
{
Banana banana = new Banana();//<=====How can you instantiate it inside this class? I don't want other assemblies to instantiate it.
...
return banana;
}
}
这应该有效。只能在自己的类中实例化Banana类,而不能在其他类中实例化。我只需要一个私有构造函数和一个静态方法即可实例化。