how to restrict setting a property of innerclass j

2020-05-09 17:12发布

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

2条回答
smile是对你的礼貌
2楼-- · 2020-05-09 17:35

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; }
    }
}
查看更多
淡お忘
3楼-- · 2020-05-09 17:37

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; }
    }
}
查看更多
登录 后发表回答