Readonly field that could be assigned a value outside constructor

后端 未结 7 1982
清酒与你
清酒与你 2021-01-22 16:19

Is there a way to have a private readonly field in a class that could be assigned a value anywhere in the class, but only once??

That is, I am looking for a private read

7条回答
  •  半阙折子戏
    2021-01-22 16:42

    This looks like a good candidate for declaration assignment or singleton.

    public class SomeClass {
        private readonly Type t = typeof(SomeClass);
    }
    

    Or otherwise, like the others said, make an internal or so property with only a setter, then assign a value to it.

    public class SomeClass {
        private Type t;
    
        internal Type Type {
            set {
                if (t == null) t = value;
            }
        }
    }
    

提交回复
热议问题