Expression Is a value and therefore cannot be the target of an assignment

后端 未结 2 949
悲&欢浪女
悲&欢浪女 2020-12-20 02:47

I ran into an issue using a struct today that caught me off guard, and I was hoping someone could shed some light on it for me.

I have a struct defined like this:

相关标签:
2条回答
  • 2020-12-20 03:00

    It is probably because you are exposing Payment as readonly, no setter. Since a struct is a value-type, it won't allow you to set a property on the struct if the struct is readonly.

    Adding a setter should fix the issue.

    I would also consider changing PaymentDetail to a class. I only use structs when it is a very basic value. Something with three properties like this especially if one is a string should be a class.

    0 讨论(0)
  • 2020-12-20 03:03

    First - don't have mutable structs (i.e. a struct where you can change the values after construction, via setters etc). That is the primary cause of confusion here.

    The point is; when you call a property (like Payment) you get a copy of the value (in your local stack area). For a class, that is a copy of the reference (no problem). For a struct it is a copy of the struct itself. Any changes to that value will be discarded, so the compiler has stopped you from losing data.

    When it is a public field, you are mutating the original value directly, which is why it doesn't mind. But mutating structs really isn't a good idea.

    Make PaymentDetail a class; that is the correct solution here...

    In .NET, structs aren't "objects without behaviour" - they are "value-types". Things like "a currency/value pair", "a time range", etc might make valid structs - but not PaymentDetail.

    0 讨论(0)
提交回复
热议问题