是否有访问修饰符组合或模式限制类及其包含类
本文关键字:包含类 模式 访问 组合 是否 | 更新日期: 2023-09-27 18:15:10
访问修饰符列表给出了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
}
}
有办法吗?同样,可能不是字面上的访问修饰符,除非我在上面链接的页面上错过了一个神奇的组合,但我可以使用一些模式来实现它,如果不是现实?
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
}
}