我有以下代码:
class A
{
public C GetC()
{
return new C();
}
}
class B
{
//has access to A but can not create C. Must ask A to create C.
private void method()
{
A a = new A();
C c = a.GetC();//Ok!
C c2 = new C();//Not allowed.
}
}
class C
{
}
应该在 C 上使用什么访问修饰符,以便只能通过 A 访问它? (只有A类知道如何正确初始化C类) 或者有更好的解决方案吗?
最佳答案
如果将 A 设为 C 中的嵌套类,它应该可以工作。
public class B
{
//has access to A but can not create C. Must ask A to create C.
private void method()
{
var a = new C.A();
var c = a.GetC();//Ok!
var c2 = new C();//Not allowed.
}
}
public class C
{
private C()
{
}
public class A
{
public C GetC()
{
return new C();
}
}
}
关于c# - 类嵌套和访问修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10599037/