【问题标题】:Is there an access modifier combination or pattern limiting to the class and its containing class?是否存在限制类及其包含类的访问修饰符组合或模式?
【发布时间】:2014-07-27 17:16:53
【问题描述】:

list of access modifiers 为我们提供 publicprivateprotectedinternalprotected internal。在编写嵌套类时,我发现自己想要一个魔术修饰符组合(不太可能)或编码模式,它给我privateprotected,但包含类也可以访问。有这种事吗?

示例 - 类或其容器类中的公共属性仅代码可以设置:

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
    }
}

有没有办法做到这一点?同样,除非我在上面链接的页面上错过了一个神奇的组合,否则可能不是字面上的访问修饰符,但如果不是现实,我可以使用一些模式来使其生效?

【问题讨论】:

    标签: c# access-modifiers


    【解决方案1】:
    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
        }
    }
    

    【讨论】:

    • 非常好。我知道有一种使用接口的方法。对我来说缺少的是建造者。谢谢!
    猜你喜欢
    • 2016-03-12
    • 2020-02-05
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 2014-01-02
    相关资源
    最近更新 更多