how to restrict setting a property of innerclass just from the outer class in c#

旧时模样 提交于 2019-12-02 23:00:27

问题


I have the nub of the code like this:

public class OuterClass
{
    public static InnerClass GetInnerClass()
    {
        return new InnerClass() { MyProperty = 1 };
    }

    public class InnerClass
    {
        public int MyProperty { get; set; }
    }
}

what is the solution to property named MyProperty just be settable from the InnerClass and the OuterClass, and out of these scopes, MyProperty just be readonly


回答1:


There is no protection level for that. internal is the tightest you can use, which is limited to files in the same assembly. If you cannot make it a constructor parameter as has been proposed, you could use an interface:

public class OuterClass
{
    public static InnerClass GetInnerClass()
    {
        return new InnerClassImpl() { MyProperty = 1 };
    }

    public interface InnerClass
    {
        int MyProperty { get; }
    }
    private class InnerClassImpl : InnerClass
    {
        public int MyProperty { get; set; }
    }
}



回答2:


I'm afraid there is no access modifier which allows that. You can create IInnerClass interface and make the property readonly within interface declaration:

public class OuterClass
{
    public static IInnerClass GetInnerClass()
    {
        return new InnerClass() { MyProperty = 1 };
    }

    public interface IInnerClass
    {
        int MyProperty { get; }
    }

    private class InnerClass : IInnerClass
    {
        public int MyProperty { get; set; }
    }
}


来源:https://stackoverflow.com/questions/21439102/how-to-restrict-setting-a-property-of-innerclass-just-from-the-outer-class-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!