允许访问但阻止外部类实例化嵌套类 [英] Allow access to but prevent instantiation of a nested class by external classes
问题描述
我想定义一个嵌套类,容器类和外部类可以访问该嵌套类,但是我想控制嵌套类的实例化,以便只有容器类的实例才能创建嵌套类的新实例。 。
I'm looking to define a nested class that is accessible to the container class and external classes, but I want to control instantiation of the nested class, such that only instances of the container class can create new instances of the nested class.
后续代码应有望证明这一点:
The proceeding code should hopefully demonstrate this:
public class Container
{
public class Nested
{
public Nested() { }
}
public Nested CreateNested()
{
return new Nested(); // Allow
}
}
class External
{
static void Main(string[] args)
{
Container containerObj = new Container();
Container.Nested nestedObj;
nestedObj = new Container.Nested(); // Prevent
nestedObj = containerObj.CreateNested(); // Allow
}
}
嵌套
必须是公开的,以便外部
可以访问。我尝试将嵌套
的构造函数设置为受保护的,但是这会阻止 Container
创建实例,例如容器
不是嵌套
的基类。我可以将 Nested
的构造函数设置为 internal
,但是我想防止所有外部用户访问该构造函数类,包括同一程序集中的类。有办法做到吗?
Nested
must be public in order for it to be accessible by External
. I tried making the constructor for Nested
protected, however that prevents Container
from creating instances, as Container
isn't a base class of Nested
. I could set the constructor for Nested
to internal
, but I'm looking to prevent access to the constructor by all external classes, including those in the same assembly. Is there a way to do this?
如果无法通过访问修饰符实现此功能,我想知道是否可以在 Nested()中引发异常。
。但是,我不知道如何测试调用 new Nested()
的上下文。
If this cannot be achieved through access modifiers, I wonder if I could throw an exception within Nested()
. However, I don't know how to test for the context within which new Nested()
is called.
推荐答案
如何通过接口进行抽象?
How about abstraction via an interface?
public class Container
{
public interface INested
{
/* members here */
}
private class Nested : INested
{
public Nested() { }
}
public INested CreateNested()
{
return new Nested(); // Allow
}
}
class External
{
static void Main(string[] args)
{
Container containerObj = new Container();
Container.INested nestedObj;
nestedObj = new Container.Nested(); // Prevent
nestedObj = containerObj.CreateNested(); // Allow
}
}
您也可以与抽象基类相同的东西:
You can also do the same thing with an abstract base-class:
public class Container
{
public abstract class Nested { }
private class NestedImpl : Nested { }
public Nested CreateNested()
{
return new NestedImpl(); // Allow
}
}
class External
{
static void Main(string[] args)
{
Container containerObj = new Container();
Container.Nested nestedObj;
nestedObj = new Container.Nested(); // Prevent
nestedObj = containerObj.CreateNested(); // Allow
}
}
这篇关于允许访问但阻止外部类实例化嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!