C# Struct method doesn't save value if accessed by a property

后端 未结 4 847
挽巷
挽巷 2020-12-06 14:58

I need to create a structure that looks like an int (but has an extra field that I need...), so I created a new structure named TestStruct added one method (test()) that I n

4条回答
  •  自闭症患者
    2020-12-06 15:40

    It's a struct, so it's a value type - it's copied by value, not by reference.

    Properties are just syntactic sugar around method calls, Val compiles down to this:

    private TestStruct _valBackingField;
    public TestStruct get_Val {
        return _valBackingField;
    }
    

    When accessing a struct through a property, you are getting a fresh copy every time you access the Getter. When accessing a struct through a field, you are getting the same object every time.

    That's why mutable value types are considered evil™.

提交回复
热议问题