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

前端 未结 2 1142
被撕碎了的回忆
被撕碎了的回忆 2021-01-29 07:24

I have the nub of the code like this:

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


        
2条回答
  •  感情败类
    2021-01-29 07:40

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

提交回复
热议问题