Why can't I define a default constructor for a struct in .NET?

后端 未结 10 2137
时光说笑
时光说笑 2020-11-22 11:04

In .NET, a value type (C# struct) can\'t have a constructor with no parameters. According to this post this is mandated by the CLI specification. What happens i

10条回答
  •  猫巷女王i
    2020-11-22 11:47

    I haven't seen equivalent to late solution I'm going to give, so here it is.

    use offsets to move values from default 0 into any value you like. here properties must be used instead of directly accessing fields. (maybe with possible c#7 feature you better define property scoped fields so they remain protected from being directly accessed in code.)

    This solution works for simple structs with only value types (no ref type or nullable struct).

    public struct Tempo
    {
        const double DefaultBpm = 120;
        private double _bpm; // this field must not be modified other than with its property.
    
        public double BeatsPerMinute
        {
            get => _bpm + DefaultBpm;
            set => _bpm = value - DefaultBpm;
        }
    }
    

    This is different than this answer, this approach is not especial casing but its using offset which will work for all ranges.

    example with enums as field.

    public struct Difficaulty
    {
        Easy,
        Medium,
        Hard
    }
    
    public struct Level
    {
        const Difficaulty DefaultLevel = Difficaulty.Medium;
        private Difficaulty _level; // this field must not be modified other than with its property.
    
        public Difficaulty Difficaulty
        {
            get => _level + DefaultLevel;
            set => _level = value - DefaultLevel;
        }
    }
    

    As I said this trick may not work in all cases, even if struct has only value fields, only you know that if it works in your case or not. just examine. but you get the general idea.

提交回复
热议问题