错误:“无法修改返回值"C# [英] Error: "Cannot modify the return value" c#

查看:30
本文介绍了错误:“无法修改返回值"C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

public Point Origin { get;放;}原点.X = 10;//使用 CS1612 失败

<块引用>

错误信息:无法修改表达式"的返回值,因为它不是一个变量

尝试修改作为结果的值类型中间表达.因为值不是持久化的,所以值将保持不变.

要解决此错误,请将表达式的结果存储在中间值,或使用中间值的引用类型表达.

解决方案

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

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

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

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

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.

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

解决方案

This is because Point is a value type (struct).

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.

If you want to change just the X value, you need to do something like this:

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

这篇关于错误:“无法修改返回值"C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆