错误:“无法修改返回值” C# [英] Error: "Cannot modify the return value" c#
问题描述
我正在使用自动实施的属性。
我想解决以下问题的最快方法是声明我自己的后备变量?
I'm using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable?
public Point Origin { get; set; }
Origin.X = 10; // fails with CS1612
错误消息:无法修改以下项的返回值表达式,因为
不是变量
Error Message: Cannot modify the return value of 'expression' because it is not a variable
试图修改由
中间表达式产生的值类型。因为该值不是持久性的,所以值
将保持不变。
An attempt was made to modify a value type that was the result of an intermediate expression. Because the value is not persisted, the value will be unchanged.
要解决此错误,请将表达式的结果存储在
中间值中,或对中间
表达式使用引用类型。 / p>
To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.
推荐答案
这是因为 Point
是值类型(结构
)。
This is because Point
is a value type (struct
).
因此,当您访问 Origin时
属性,您正在访问该类拥有的值的副本,而不是您使用引用类型( class
),因此,如果在其上设置 X
属性,则需要在副本上设置该属性,然后将其丢弃,而使原始值保持不变。
Because of this, when you access the Origin
property you're accessing a copy of the value held by the class, not the value itself as you would with a reference type (class
), so if you set the X
property on it then you're setting the property on the copy and then discarding it, leaving the original value unchanged. This probably isn't what you intended, which is why the compiler is warning you about it.
如果只想更改 X <,这可能是编译器警告您的原因。 / code>值,您需要执行以下操作:
If you want to change just the X
value, you need to do something like this:
Origin = new Point(10, Origin.Y);
这篇关于错误:“无法修改返回值” C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!