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

后端 未结 4 849
挽巷
挽巷 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:44

    Your struct is wrong.

    For a very large number of reasons, you should never make a mutable struct.

    Just like an int or DateTime value is immutable and can never change, so too a specific value of your struct must never change at all.

    Instead, you can make functions that return a new, different value .

    Here are some reasons that mutable structs are evil:

    1. http://ericlippert.com/2008/05/14/mutating-readonly-structs/
    2. http://blog.slaks.net/2010/12/when-shouldnt-you-write-ref-this.html
    3. http://codeblog.jonskeet.uk/2010/07/27/iterate-damn-you/
    4. http://philosopherdeveloper.wordpress.com/2011/03/31/how-i-discovered-a-bug-in-the-c-compiler-part-1/

    To answer the question, Val.test() is equivalent to get_Val().test().
    Since structs are value types, `get_Val() (the automatically-generated property getter) returns a copy of the struct.
    The original struct in the private backing field is not affected.

提交回复
热议问题