list of access modifiers为我们提供了public
,private
,protected
,internal
和protected internal
。在编写嵌套类时,我发现自己想要一个魔法修饰符组合(不太可能)或编码模式,它给我private
或protected
,但包含类也有访问权限。有这样的事吗?
示例 - 类中的公共属性代码或其容器类可以设置:
public class ContainingClass {
public class NestedClass {
public int Foo { get; magic_goes_here set; }
}
void SomeMethod() {
NestedClass allow = new NestedClass();
allow.Foo = 42; // <== Allow it here, in the containing class
}
}
public class Unrelated {
void OtherMethod() {
NestedClass disallow = new ContainingClass.NestedClass();
disallow.Foo = 42; // <== Don't allow it here, in another class
}
}
有办法吗?再说一次,可能不是字面上的访问修饰符,除非我在上面链接的页面上错过了一个神奇的组合,但是如果不是现实,我可以用一些模式来使它生效吗?
答案 0 :(得分:2)
public interface IFooable
{
int Foo { get; }
}
public class ContainingClass
{
private class NestedClass : IFooable
{
public int Foo { get; set; }
}
public static IFooable CreateFooable()
{
NestedClass nc = new NestedClass();
nc.Foo = 42;
return nc;
}
void SomeMethod() {
NestedClass nc = new NestedClass();
nc.Foo = 67; // <== Allow it here, in the containing class
}
}
public class Unrelated
{
public void OtherMethod()
{
IFooable nc = ContainingClass.CreateFooable();
Console.WriteLine(nc.Foo);
nc.Foo = 42; // Now it's an error :P
}
}