Protected readonly field vs protected property

后端 未结 7 1768
广开言路
广开言路 2021-01-01 17:07

I have an abstract class and I\'d like to initialize a readonly field in its protected constructor. I\'d like this readonly field to be available in derived classes.

7条回答
  •  被撕碎了的回忆
    2021-01-01 17:20

    Using reflection you can overwrite the readonly field with ease. Using a property makes it harder because the field is hidden ( You can still do it ). So i would prefer a property which is anyway the cleaner because you can change the getter without any issues.

    If you're thinking about performance: Properties are inlined most times.

    Override readonly's

    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.OverrideReadonly("TestField", 5);
            t.OverrideReadonly("TestField2", 6);
            t.OverrideReadonly("TestField3", new Test());
        }
    }
    
    class Test
    {
        protected readonly Int32 TestField = 1;
        protected readonly Int32 TestField2 = 2;
        protected readonly Test TestField3 = null;
    
        public void OverrideReadonly(String fieldName, Object value)
        {
            FieldInfo field = typeof(Test).GetField(fieldName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            field.SetValue(this, value);
        }
    }
    

提交回复
热议问题