Overriding the Defaults in a struct (c#)

前端 未结 12 1042
感情败类
感情败类 2021-01-04 00:47

Is it possible to set or override the default state for a structure?

As an example I have an

enum something{a,b,c,d,e};

and a struc

12条回答
  •  无人及你
    2021-01-04 01:35

    There is a workaround to make this happen by using custom Property getters. Observe:

    public struct Foostruct
    {
        private int? _x;
        private int? _y;
    
        public int X
        {
            get { return _x ?? 20; } // replace 20 with desired default value
            set { _x = value; }
        }
    
        public int Y
        {
            get { return _y ?? 10; } // replace 10 with desired default value
            set { _y = value; }
        }
    }
    

    This will only work for value types (which can be wrapped with nullable) but you could potentially do something similar for reference types by wrapping them in a generic class like below:

    public class Wrapper
    {
        public TValue Value { get; set; }
    }
    
    public struct Foostruct
    {
        private Wrapper _tick;
    
        public Tick Tick
        {
            get { return _tick == null ? new Tick(20) : _tick.Value; }
            set { _tick = new Wrapper { Value = value }; }
        }
    }
    

提交回复
热议问题