gpt4 book ai didi

c# - 错误 : "Cannot modify the return value" c#

转载 作者:IT王子 更新时间:2023-10-29 03:32:59 25 4
gpt4 key购买 nike

我正在使用自动实现的属性。我想解决以下问题的最快方法是声明我自己的支持变量?

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.

To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.

最佳答案

这是因为Point是一个值类型(struct)。

因此,当您访问 Origin 属性时,您访问的是该类持有的值的副本,而不是像访问引用类型 (class),因此如果您在其上设置 X 属性,那么您就是在副本上设置该属性,然后丢弃它,保持原始值不变。这可能不是您想要的,这就是编译器警告您的原因。

如果您只想更改 X 值,您需要执行以下操作:

Origin = new Point(10, Origin.Y);

关于c# - 错误 : "Cannot modify the return value" c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1747654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com